2
class PersonEntry: NSObject {
  var firstName: String?
  var lastName: String?
}

//This errors
if (self.person.firstName?.isEmpty) {
          println("Empty")
}

//Compiler auto-correction is this
if ((self.model.firstName?.isEmpty) != nil) {
          println("Empty")
}

I understand that optional chaining returns an optional type. So I suppose my question is, how do you unwrap an optional string, to inspect it's length, without risking a crash ?

  • Similar question (with two different solutions) here: [Evaluate Bool property of optional object in if statement](http://stackoverflow.com/questions/26910229/evaluate-bool-property-of-optional-object-in-if-statement). – Martin R Mar 04 '15 at 21:03

2 Answers2

10

I presume that if the property is nil then you want to consider it empty - in that case you can use the nil coalescing operator in combination with the first version of the if statement:

if self.person.firstName?.isEmpty ?? true {
          println("Empty")
}

If firstName is nil, the expression evaluates to the right side of the coalescing operator, true - otherwise it evaluates to the value of the isEmpty property.


References:

Nil Coalescing Operator

Optional Chaining

Antonio
  • 71,651
  • 11
  • 148
  • 165
0

Another trick.

var str: String?
str = "Hello, playground"

println(count(str ?? ""))
iwat
  • 3,591
  • 2
  • 20
  • 24