我有一個testFunction嘗試獲取用于制作它們的陣列的值。由于某些型別符合CustomStringConvertible而某些型別符合CustomDebugStringConvertible我為每種型別創建了 2 個具有相同名稱的函式。但是我看到 Xcode 抱怨模棱兩可的問題,然后我使用了不同的名稱,我希望保留像testFunction這樣的名稱并且沒有testFunction1和testFunction2。
這是我的代碼:
func testFunction1<T: CustomStringConvertible>(_ values: T...) {
var array: [String] = [String]()
values.forEach { value in
array.append(value.description)
}
// other code to use array later ...
}
func testFunction2<T: CustomDebugStringConvertible>(_ values: T...) {
var array: [String] = [String]()
values.forEach { value in
array.append(value.debugDescription)
}
// other code to use array later ...
}
問題在這里:我可能必須接收具有不同型別的混合值!Swift 列印函式可以處理它,但我的 2 個函式不能只接受符合CustomStringConvertible或CustomDebugStringConvertible 的型別!我正在嘗試解決混合型別問題,這樣我的 testFunction 就可以像列印一樣接受混合值。
很重要!我希望用我正在使用的方法解決這個問題。我不是在尋找某種涵蓋CustomStringConvertible和CustomDebugStringConvertible的超級協議。
用例:
print("Hello, world!", 1, CGFloat.pi, CGSize.zero)
testFunction1("Hello, world!", 1, CGFloat.pi, CGSize.zero)
testFunction2("Hello, world!", 1, CGFloat.pi, CGSize.zero)
uj5u.com熱心網友回復:
這是一種不使用泛型的方法
func testFunction1(_ values: Any...) {
var array: [String] = [String]()
values.forEach { value in
switch value.self {
case is CustomStringConvertible:
array.append((value as! CustomStringConvertible).description)
case is CustomDebugStringConvertible:
array.append((value as! CustomDebugStringConvertible).debugDescription)
default:
break
}
}
// other code to use array later ...
}
uj5u.com熱心網友回復:
這里的問題是你的陣列。將您的陣列設定為var array: [T] = []
編輯:嘗試洗掉通用約束。
func testFunction1(_ values: CustomStringConvertible...) {
}
func testFunction2(_ values: CustomDebugStringConvertible...) {
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/401325.html
標籤:迅速
