gpt4 book ai didi

arrays - Swift:按键引用数组元素

转载 作者:搜寻专家 更新时间:2023-11-01 06:18:25 24 4
gpt4 key购买 nike

我已经编写了自己的小函数来使用键在数组中查找元素。但我确信在 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})

最佳答案

在 Swift 3(Xcode 8,目前是 beta 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.
}

使用 Sequence 协议(protocol)的 first(where:) 方法:

/// 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?

关于arrays - Swift:按键引用数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39236301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com