简体   繁体   中英

How to check if a Generic type is nil in 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])

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM