Swift 展开非可选类型

Swift unwrapping non optional type

我有 swift 可选的未包装变量 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 包含可选值,但当我尝试强制展开此可选值时,它会抛出错误 "Cannot force unwrap non optional type 'String'"。

你是对的,phone打印时不应该是可选类型。正如 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 变量上时,检查它告诉您的有关 phone 变量类型的信息。)