如何在Swift中检查Generic类型是否为nil

时间:2022-11-25 16:53:02

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!

我正在尝试将所有函数从python复制到swift,从检查列表中的任何nill项开始,但我很难检查可选项。出于某种原因,我可以发送一个可选的字符串(例如字符串),即使它说它是nil,它仍然通过if语句传递,它不在函数之外。关于如何处理这种或其他方式的任何建议?谢谢!

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])

1 个解决方案

#1


2  

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?]

函数的参数应该是一个选项数组[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.

直接将元素与nil进行比较也可能是有益的。可以将比较抽象为闭包,就像过滤函数使用的那样。

func all<T>(array: [T?]) -> Bool {
    for element in array {
        if element==nil {
            return false
        }
    }
    return true
}

#1


2  

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?]

函数的参数应该是一个选项数组[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.

直接将元素与nil进行比较也可能是有益的。可以将比较抽象为闭包,就像过滤函数使用的那样。

func all<T>(array: [T?]) -> Bool {
    for element in array {
        if element==nil {
            return false
        }
    }
    return true
}