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?
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?
On
You can try using if let
if let name = obj.name as? String
{
print(name)
}
else
{
print("name is nil")
}
On
It's not too clear what you're asking ... But from what I can tell you are looking for a way to handle the case where obj.name is nil.
You could write it like:
if obj.name == nil {
// I am nil
} else {
// I am not nil
}
or if you needed to capture the non-optional value how about:
if let name = obj.name {
print(name) // I am not nil
} else {
// I am nil
}
And im not sure why you would cast it to Any - generally if you can stick to concrete types you will save yourself a headache and pain down the road.
On
For example if you have your Person object:
class Person {
var name: String?
}
let person = Person()
You can use name property in a few ways: using if-let or ? operator.
// if-let construction
if let personName = person.name {
print(personName.uppercased())
}
// `?` operator example
let uppercasedPersonName: String? = person.name?.uppercased()
For your case if-let is more likely to be what you want.
There are 2 ways to handle nil in swift:
1. Use of if-let statement
You can also check type of
obj.namevariable here as2. Use of guard-let statement
Difference between both condition is that with
if-letyou code will continue executing with next line of code after condition fails( if object is nil), butguard-letwill stop execution and will throw return.Note: Default operator
??You can also implement default "
operator: ??" for assigning a default value like: