我编写了自己的小函数,使用键在数组中查找元素。但我确信在Swift中有一个可以使用的实现来将它放在一行中。任何提示?
func objectAtKey(array: [T], key: String) -> T? {
for element in array {
if element.name == key {
return element
}
}
return nil
}
我也知道函数indexOf,但这返回一个索引,我必须用于进一步访问。我认为这个比较慢:
let index = array.indexOf({$0.name == key})
答案 0 :(得分:3)
在Swift 3(Xcode 8,目前是测试版6)中你可以做到
if let el = array.first(where: { $0.name == key }) {
// `el` is the first array element satisfying the condition.
// ...
} else {
// No array element satisfies the condition.
}
使用first(where:)
协议的Sequence
方法:
/// Returns the first element of the sequence that satisfies the given
/// predicate or nil if no such element is found.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element is a match.
/// - Returns: The first match or `nil` if there was no match.
public func first(where predicate: (Element) throws -> Bool) rethrows -> Element?
答案 1 :(得分:1)
我认为这里最好的解决方案是使用indexOf
和Predicate
编写的代码。我会这样写的:
let array = ["Foo", "Bar", "Test"]
if let i = array.indexOf({$0 == "Foo"}) {
print(array[i])
}
如果您需要,则处理该值是否存在。
答案 2 :(得分:0)
试试这个:
let element = array.filter{ $0.name == key }.first