我有一个用于保存数据的结构;
struct MyStruct {
var age: Int
var name: String
}
Run Code Online (Sandbox Code Playgroud)
我做了一个这样的数组并用数据填充它;
var myArray = [MyStruct]()
myArray[0] = MyStruct(age: 26, name: "John")
myArray[1] = MyStruct(age: 35, name: "Smith")
Run Code Online (Sandbox Code Playgroud)
如何找到myArray包含名称"Smith" 的元素的索引?
编辑:这里有更多关于我需要使用Losiowaty的新代码找到位置的上下文;
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let selection = tableView.cellForRow(at: indexPath)?.textLabel
let name = selection!.text!
let location = myArray.index(where: { $0.name == name})
//additional code to comply with the function and return, unneeded for this context
}
Run Code Online (Sandbox Code Playgroud)
Los*_*aty 13
你可以使用index(where:)方法.一个简单的例子:
let index = myArray.index(where: { $0.name == "Smith" })
Run Code Online (Sandbox Code Playgroud)
在没有这样的元素的情况下,该方法将返回nil.
通过编辑的更多上下文,最好(即最安全)的方式是这样的:
if let name = selection?.name {
if let location = myArray.index(where: { $0.name == name }) {
// you know that location is not nil here
}
}
Run Code Online (Sandbox Code Playgroud)
来源 - https://developer.apple.com/reference/swift/array/1688966-index
对于 Swift 4: index(where:) 已被弃用,所以现在使用 firstIndex:
let index = firstIndex(where: { $0.name == "Smith" })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3782 次 |
| 最近记录: |