I'm currently working with an SDK where methods return an optional array of objects with optional properties. Only the array itself is optional, it will either be nil or always contain non-optionals. I'm struggling to find a cleaner way to unwrap optional properties for each non-optional in the array:
class Person {
var id: String?
}
func someOptionalArrayOfPeople() -> [Person]? {
// returns either nil or some array of Person objects
}
let people = someOptionalArrayOfPeople()
if let unwrappedPeople = people {
// 1
for person in unwrappedPeople {
if let id = person.id {
print(id) // too many nested statements
}
}
// 2
for person in unwrappedPeople where person.id != nil {
print(person.id!) // stil force unwrapping
}
}
For option 1, I'm not thrilled about unwrapping the initial optional array, and I feel that there should be a way to skip the unwrapping of the id
. Option 2 attempts to do that with a where
clause, but the compiler isn't smart enough to determine that person.id
is non-nil
even if we explicitly check that id != nil
.
What are my "Swifty" options for unwrapping optional properties on an optional array of objects? I am using Swift 2.2 with Xcode 7.3.1.