2016-11-15 28 views
1

我迅速可选展开变量phone但是当我尝试使用这个变量它给可选裹得像下面斯威夫特展开非可选类型

if let phone = self!.memberItem!.address?.mobile { 
    print(phone) // Optional(+123232323) 
    //error "Cannot force unwrap non optional type 'String'". 
    print(phone!) 
} 

struct Address{ 

    var tel: String? 
    var fax: String? 
    var mobile: String? 
    var email: String? 

} 

phone包含可选值,但是当我试图强行解开这个可选它会抛出错误“不能强制展开非可选类型'String'”。

+1

可能[什么是Swift中的可选值?](http://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift) – Idan

+4

您的地址?.mobile已包含字符串带有可选的前缀。检查这个属性的setter。 –

+6

听起来就像你已经设法分配'移动'*实际*字符串“可选(+123232323)”,可能通过使用字符串插值或'字符串(描述:)'在一个可选的 - 请告诉我们你是如何'重新分配这个属性。 – Hamish

回答

1

你是对的,打印时手机不应该是可选类型。正如Hamish在上面评论的那样,在将值分配给mobile属性时听起来像是出错了。

这里有一个简单的例子:

struct Person { 
    let address: Address? 
} 

struct Address { 
    let mobile: String? 
} 

let dude: Person? = Person(address: Address(mobile: "555-1234")) 

if let phone = dude?.address?.mobile { 
    print(phone) // Prints plain "555-1234", without "Optional" 
} 

(如果你使用的XCode,检查它告诉你关于phone变量的类型,当你把你的光标在编辑器)