Wimal Weerawansa Wimal Weerawansa - 4 months ago 26
Swift Question

Swift unwrapping non optional type

I have swift optional unwrapped variable

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'".

struct Address{

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


contains optional value, but when i try to force unwrap this optional it throws error "Cannot force unwrap non optional type 'String'".

jjs jjs

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.)