Search code examples
swiftoption-typeforced-unwrapping

Why optional is not giving warning or asking for force unwraping?


struct SomeStruct {
    var optVar : String?
    var nonOptVar : String = "Hello"
    var optvar2 : String!
}

let obj2 = SomeStruct(optVar: "a", nonOptVar: "b", optvar2: "c")
let a = obj2.optVar // why it is not asking for force unwraping
let b = obj2.nonOptVar
let c = obj2.optvar2
print(a)
print(b)
print(c)

Please share your view on this. But while I use optionals in project generally it gives warling 'Expression implicitly coerced from String? to Any'


Solution

  • This is mainly due to type inference. Here:

    let a = obj2.optVar
    

    a is inferred to be of type String?, because that's the type of the expression on the right, isn't it?

    // basically this:
    let a: Optional<String> = obj2.optVar
    

    An optional value can be assigned to a variable of an optional type. Nothing wrong with that.

    If you declare a to be of type String, however, you need to unwrap it:

    let a: String = obj2.optVar // error!
    

    The warning 'Expression implicitly coerced from String? to Any' appears when you are trying to put an optional value into a variable of type Any, like this:

    let a: Any = obj2.optVar // warning!