I'm trying to copy the all function from python to swift, starting off with checking for any nill items in a list, but I'm having a tough time checking optional items. For some reason I can send a optional string (string for example) and even though it says it's nil it still passes thru an if statement, which it doesn't outside of the function. Any advice about how to deal with this or another way of doing it? Thanks!
func `all`<T>(array: [T]) -> Bool {
for item in array {
if item as Any? {
println(item) // Says Nil >.<
}
var test: T? = item
if test {
println("Broken") // Prints broken :(
}
}
return true
}
var t: String?
all([t])
It's unclear to me exactly what you're trying to test, but maybe this will help.
The parameter to the function should be an Array of optionals [T?]
It may also be beneficial to directly compare elements to nil
. The comparison could be abstracted to a closure much like the filter
function uses.
func all<T>(array: [T?]) -> Bool {
for element in array {
if element==nil {
return false
}
}
return true
}
I know this is old, but it still being searched for. Just spent couple of hours looking for a solution and I think I have finally found one.
if (item as AnyObject) is NSNull {
//value is nil
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With