Swift optional downcasting as Any

302 Views Asked by At

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?

4

There are 4 best solutions below

0
Ankit Jayaswal On BEST ANSWER

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 ?? ""
0
Shehata Gamal On

You can try using if let

if let name = obj.name as? String
{
   print(name)
}
else
{
   print("name is nil")
}
0
Oliver Atkinson 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.

0
danshevluk 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.