1

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

Wimal Weerawansa
  • 309
  • 2
  • 15
  • 33
  • 1
    Possible duplicate of [What is an optional value in Swift?](http://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift) – Idan Nov 15 '16 at 11:50
  • 4
    Your `address?.mobile` already contains string with optional prefix. Check setter for this property. – Max Potapov Nov 15 '16 at 11:50
  • 6
    Sounds like you've managed to assign `mobile` the *actual* string "Optional(+123232323)", probably through the use of string interpolation or `String(describing:)` on an optional – please show us how you're assigning this property. – Hamish Nov 15 '16 at 11:51

1 Answers1

1

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

jjs
  • 1,338
  • 7
  • 19