Wimal Weerawansa Wimal Weerawansa - 23 days ago 9
Swift Question

Swift unwrapping non optional type

I have swift optional unwrapped variable

phone
but when i try to use this variable it gives optional wrapped like below

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
contains optional value, but when i try to force unwrap this optional it throws error "Cannot force unwrap non optional type 'String'".

jjs jjs
Answer

You're correct, phone shouldn't be an Optional type when printing it. As Hamish commented above, it sounds like something went wrong when assigning the value to the mobile property.

Here's a simple example:

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"
}

(If you're using XCode, check what it tells you about the phone variable's type when you put your cursor on it in the editor.)