Aswath Aswath -4 years ago 73
iOS Question

Swift 3: How can I shorten an optional check coupled with a condition check of that optional?

Consider this example. The else if condition checks on the string object looks big and chunky.

class A { var bObject = B() }

class B { var cObject = C() }

class C {
var flag = FALSE
var stringObj: String? = "Hello"
}

var aObject = A()

if aObject.bObject.cObject.flag == TRUE {

//do something
}
else if aObject.bObject.cObject.stringObject != nil && aObject.bObject.cObject.stringObj!.characters.count > 0 && aObject.bObject.cObject.stringObj! == "Hello" {

//do something
}
else {

}


I'd like to use something like the one below, where the optionally bound variable is used in the same conditional check. But the code wouldn't compile for obvious reasons

else if let unwrappedOptional = aObject.bObject.cObject.stringObj && unwrappedOptional.characters.count > 0 && unwrappedOptional == "Hello" {

//do something
}


Is there a more elegant way to handle this?

Answer Source

You can use condition with if let this way.

else if let unwrappedOptional = aObject.bObject.cObject.stringObj, unwrappedOptional == "Hello" {

    //do something
}

Note: No need to compare characters.count to 0 because "do something" will only execute if unwrappedOptional is equal to Hello.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download