我想創建一個可以採用可選參數的泛型函數。 這是我到目前爲止有:Swift - 以可選參數的泛型函數的參數爲零
func somethingGeneric<T>(input: T?) {
if (input != nil) {
print(input!);
}
}
somethingGeneric("Hello, World!") // Hello, World!
somethingGeneric(nil) // Errors!
它能與String
如圖所示,但不與nil
。 使用它與nil
提供了以下兩個錯誤:
error: cannot invoke 'somethingGeneric' with an argument list of type '(_?)'
note: expected an argument list of type '(T?)'
我在做什麼錯了,我應該如何正確申報/使用這個功能嗎?此外,我想保持功能的使用盡可能簡單(我不想做類似nil as String?
的東西)。
你的'somethingGeneric(輸入:T?)'func仍然不接受nil作爲一個值,但它只是通過空函數並且isn'因爲這個函數沒有做任何事情,所以如果你用nil調用func,它會通過函數'input:NilLiteralConvertible'作爲參數,但是如果你用一個nil可選來調用它,比如就像說x:String?一樣,它會通過'input:T?'作爲參數來處理func你將不得不復制你的無處理邏輯。 –
@WillM。 'somethingGeneric(input:T?)'不需要'nil'; 'somethingGeneric(input:NilLiteralConvertible?)'。我選擇這種方式,因爲它適用於所有三種,但你是對的,我可以轉換'somethingGeneric (input:T?)'不採取可選,但它會打破'零作爲字符串?'(我只是沒有並不希望它是這樣調用函數的要求)。 –
Coder256
請注意 - 例如 - 'let ptr:UnsafePointer? = ...; somethingGeneric(ptr)會調用* second *函數,因爲UnsafePointer是NilLiteralConvertible而第二個泛型函數更具體。 –