有没有办法获取过滤索引的列表而不是对象。
class Object
{
var name
var goal
}
var array<Object> = Array<Object>()
var filteredIndexes = array.filter{$0.name = "Sane"} // How to implement this?
答案 0 :(得分:2)
有几种方法可以实现您的目标。例如,您可以过滤$ brew install rbenv ruby-build
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
$ source ~/.bash_profile
而不是数组本身。
自包含的例子:
transitionToRoute
答案 1 :(得分:2)
let animals = ["cat", "dog", "cat", "dog", "cat"]
let indexes = animals.enumerated().filter({ return $1 == "cat" }).map { return $0.offset }
print(indexes)
打印出[0, 2, 4]
答案 2 :(得分:1)
作为Lame said above,可以调整Return an array of index values from array of Bool where true的解决方案 对于这种情况:
let filteredIndices = objects.enumerated().flatMap { $0.element.name == "Sane" ? $0.offset : nil }
还可以定义自定义扩展程序
extension Sequence {
func indices(where predicate: (Element) -> Bool ) -> [Int] {
return enumerated().flatMap { predicate($0.element) ? $0.offset : nil }
}
}
然后用作
let filteredIndices = objects.indices(where: { $0.name == "Sane" })
备注:在Swift 4.1中,此flatMap()
方法已重命名为compactMap()