Reputation: 22939
I want to loop through a list of objects, which is potentially nil
.
So I want to do this:
if let versions = try? moc?.executeFetchRequest(req) as? [Version]{
for v in versions{
// Do stuff
}
}
I do assume that I would then have an array of Version
objects. However, the compiler won't accept this and tells me I have to force-unwrap the versions
variable in order to loop through them. So I end up with the for loop like so:
for v in versions!{
// Do stuff
}
The comiler error in Xcode 7.2
Value of optional type
[Version]?
not unwrapped; did you mean to use!
or?
?
Side note:
I also wonder why swift won't let me loop through [Anyobject]?
, since swift could easily unwrap the array and then loop through or not loop at all if the optional is nil:
for x in someOptionalArray{
// Do stuff
}
Upvotes: 0
Views: 89
Reputation: 21154
The problem here is with try? version that you are using. It returns optional [Version] array. So, either use forced try using try! like this,
if let versions = try! moc?.executeFetchRequest(req) as? [Version]{
for v in versions{
// Do stuff
}
}
or, then you can also use chained if let pattern to unwrap the result like this,
if let optionalResult = try? moc?.executeFetchRequest(fetchRequest) as? [Version], let result = optionalResult {
for result in result {
}
}
Or then you can also use try/catch block.
Upvotes: 1
Reputation: 70113
Because using try?
adds a layer of Optional to an already Optional value.
I would use the normal try
instead, for example:
do {
if let mocOK = moc, versions = try mocOK.executeFetchRequest(req) as? [Version] {
for v in versions {
// Do stuff
}
}
} catch let error as NSError {
print(error)
}
Also, no, you can't loop over an Optional array, because it is not an Array, it is an Optional, and Optionals don't conform to the sequence type. You have to safely unwrap first.
Upvotes: 1