Arrayを拡張し、メソッドの引数としてクロージャを渡すだけです。
extension Array {
mutating func removeAll(where isExcluded: (Element) -> Bool) {
for (index, element) in enumerated().reversed() {
if isExcluded(element) {
remove(at: index)
}
}
}
}
RangeReplaceableCollectionを拡張する別のオプション:
extension RangeReplaceableCollection {
mutating func removeAll(where isExcluded: (Element) -> Bool) {
for index in indices.reversed() where isExcluded(self[index]) {
remove(at: index)
}
}
}
あなたが(条件に基づいて、配列の要素を削除する)フィルタの逆として動作するように変異メソッドを作成したいとしましょう
用途:
var array = [1, 2, 3, 4, 5, 10, 20, 30]
array.removeAll(where: {$0 > 5})
print(array) // [1, 2, 3, 4, 5]
スウィフトのほとんどのデータ型は構造体です。配列、文字列、ダブル、イント、日付。あなたは正確に何をしようとしていますか? –
@Leo Dabus Hmm ...、Somefunc(入力:配列、クロージャ:{....})ではなく、array.somemethod({closure})のようにしたい。 – kimjinyam
あなたは配列を拡張し、クロージャをメソッドの引数 –