Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a Generic type is nil in Swift

Tags:

swift

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])
like image 558
GnarGnar Avatar asked Jul 27 '14 01:07

GnarGnar


2 Answers

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
}
like image 79
Fabian Avatar answered Oct 07 '22 23:10

Fabian


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
}
like image 27
Raimundas Sakalauskas Avatar answered Oct 07 '22 23:10

Raimundas Sakalauskas