iosswiftswift3optional-variables

Swift optional downcasting as Any


If we are trying access optional object property can we do like this -

var obj: Person

var str = obj.name? as Any

is this the right way to handle a nil case in swift3?


Solution

  • There are 2 ways to handle nil in swift:

    1. Use of if-let statement

        var obj: Person
        if let name = obj.name {
            var str = name
        }
    

    You can also check type of obj.name variable here as

        var obj: Person
        if let name = obj.name as? String {
            var str = name
        }
    

    2. Use of guard-let statement

        var obj: Person
        guard let name = obj.name as? String else {
            return
        }
    

    Difference between both condition is that with if-let you code will continue executing with next line of code after condition fails( if object is nil), but guard-let will stop execution and will throw return.

    Note: Default operator ??

    You can also implement default "operator: ??" for assigning a default value like:

    var str = obj.name ?? ""