我正在嘗試對 Array 進行擴展,請參見下文
extension Array {
func mapThenUnique<T: Comparable>(f: (Element) -> T) -> Array<T> {
var mapped: Array<T> = Array(self.filter( f(self) ))
/* Three Errors /\
1) Cannot assign value of type '[Element]' to type 'Array<T>'
2) Cannot convert value of type 'Array<Element>' to expected argument type 'Element'
3) Cannot convert value of type 'T' to expected argument type '(Element) throws -> Bool' */
var noDups: Array<T> = []
for element in mapped {
if (!noDups.contains(where: element)) { noDups.append(element) }
// Error - Cannot convert value of type 'T' to expected argument type '(T) throws -> Bool'
}
return noDups
}
}
我知道 noDups 陣列必須是 'T' 型別,因為這是正確的回傳型別,請參閱下面的示例了解 mapThenUnique 的作用:
["abc", "Hi", "AbC"].mapThenUnique { $0.lowercased() } -> ["abc", "hi"]
[2, 9, -9, 3].mapThenUnique { Int($0) * $0 } -> [4, 9, 81]
// notice that there are no duplicates in the array
但我不確定為什么會收到這些錯誤訊息。'(Element) throws -> Bool' 是什么意思?任何幫助將不勝感激!
編輯:我現在清醒的大腦意識到它應該是地圖而不是過濾器,謝謝@Sulthan。
extension Array {
func mapThenUnique<T: Comparable>(f: (Element) -> T) -> Array<T> {
var mapped: Array<T> = self.map{ f($0) }
var noDups: Array<T> = []
for element in filtered {
if (!noDups.contains(where: element)) { noDups.append(element) }
// Error - Cannot convert value of type 'T' to expected argument type '(T) throws -> Bool'
}
noDups.sort()
// this works for the numerical test cases but not for ["abc", "Hi", "AbC"] which returns ["abc", "hi"], idk why it does
return noDups
}
}
我仍在嘗試弄清楚 for 回圈中的錯誤訊息的含義。哦,這是一個硬體任務。
uj5u.com熱心網友回復:
如果您使用 Set 并使其成為 Hashable 而不是 Comparable,則相當簡單
extension Array {
func mapThenUnique<T: Hashable>(f: (Element) -> T) -> [T] {
var seen = Set<T>()
return map { f($0) }.filter { seen.insert($0).inserted }
}
}
["abc", "Hi", "AbC"].mapThenUnique { $0.lowercased() } // ["abc", "hi"]
[2, 9, -9, 3].mapThenUnique { Int($0) * $0 } // [4, 81, 9]
或者如果您不在乎原始訂單
Set(["abc", "Hi", "AbC"].map { $0.lowercased() }) // ["abc", "hi"] or ["hi", "abc"]
Set([2, 9, -9, 3].map { Int($0) * $0 }) // Some random order of [4, 81, 9]
在 Swift 中執行此操作的更“正確”方法是在 Collection
extension Collection where Element: Hashable {
func mapThenUnique(f: (Element) -> Element) -> [Element] {
var seen = Set<Element>()
return map { f($0) }.filter { seen.insert($0).inserted }
}
}
雖然我認為具有做兩件事的功能是“糟糕的形式”,但我個人的偏好是
extension Collection where Element: Hashable {
func unique() -> [Element] {
var seen = Set<Element>()
return filter { seen.insert($0).inserted }
}
}
["abc", "Hi", "AbC"].map { $0.lowercased() }.unique()
(同樣,假設您想保留訂單。否則,只需使用 Set!)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/360585.html
標籤:迅速
上一篇:如何有效地級聯CIFilters
下一篇:使用Swift5.5進行方法混合
