-4

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?

Oliver Atkinson
  • 7,970
  • 32
  • 43
srus2017
  • 394
  • 2
  • 14
  • Form perspective of real life does a person ever have no name? Consider `name` to declare as non- optional. This makes the issue groundless. – vadian Mar 29 '18 at 15:20
  • I have just given the example here to clear my doubt – srus2017 Mar 29 '18 at 16:27

4 Answers4

1

You can try using if let

if let name = obj.name as? String
{
   print(name)
}
else
{
   print("name is nil")
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

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.

Oliver Atkinson
  • 7,970
  • 32
  • 43
1

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 ?? ""
Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36
0

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.

danshevluk
  • 303
  • 3
  • 9