![](/img/trans.png)
[英]How to return a default value for a generic parameter in a function in Swift?
[英]Set default or nil value to the generic type parameter of the function
假設我有一個協議
protocol TestProtocol {
}
此外,有一個結構並從協議繼承它。
struct StructOne: TestProtocol {
}
現在,我有一個視圖控制器類並創建了一個通用函數來接受一組TestProtocol
類型對象(這是一個通用參數)。 這是用於 SDK API 調用的傳遞參數。
但是在一些 API 調用中,我不需要傳遞這個參數數組。 所以,我只想在函數定義中設置 nil 值或默認空數組。
這是課堂
class TestViewController: UIViewController {
// func genericCall<T: TestProtocol>(param: [T] = []) { // Not work
// func genericCall<T: TestProtocol>(param: [T]? = nil) { // Not work
func genericCall<T: TestProtocol>(param: [T]?) {
if param?.isEmpty == true {
print("Empty Param Calling")
} else {
print("With Param Calling")
}
}
override func viewDidLoad() {
super.viewDidLoad()
let param = [StructOne(), StructOne()]
self.genericCall(param: param) // This one work
self.genericCall(param: [] as [StructOne]) // This one also work. But want default value in function
self.genericCall(param: nil) // Not work : Error - Generic parameter 'T' could not be inferred
// self.genericCall() // Not work with default empty value : Error - Generic parameter 'T' could not be inferred
}
}
我收到此編譯時錯誤:無法推斷通用參數“T”
我可以在函數調用期間設置一個空數組。 這是這里提到的
我還檢查了這個鏈接,如果只有 T 類型,它允許設置 nil 值,但這里是 T ([T]) 的數組。
有沒有辦法設置默認的 nil 值或任何其他方法來設置默認的空數組? 所以我們可以避免向每個函數調用傳遞一個空數組。
更新:
我不能這樣用。 由於 SDK 函數調用不允許我傳遞參數值。
func genericCall(param: [TestProtocol] = []) {
// param: Not allowed me to pass to the sdk call function.
if param.isEmpty == true {
print("Empty Param Calling")
} else {
print("With Param Calling")
}
}
注意:這是一個演示代碼。 實際上,我正在使用 SDK 之一,因此我無法在協議中進行更多更改。
在這種情況下nil
太寬泛了,因為編譯器無法推斷出哪個[T]?
它應該適用零。
您需要在此處明確指定Optional
通用參數:
self.genericCall(param: [StructOne]?.none)
您可以創建一個泛型方法,將您的泛型類型限制為RangeReplaceableCollection
並將其Element
為您的TestProtocol
。 它能工作的原因是RangeReplaceableCollection
要求符合它的協議提供一個空的初始化程序:
protocol TestProtocol { }
struct StructOne: TestProtocol { }
class TestViewController: UIViewController {
func genericCall<T: RangeReplaceableCollection>(param: T = .init()) -> T where T.Element: TestProtocol {
if param.isEmpty {
print("Empty Param Calling")
} else {
print("With Param Calling")
}
return param
}
override func viewDidLoad() {
super.viewDidLoad()
let result: [StructOne] = genericCall() // This one work
print(result)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.