我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?
我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。
当前回答
这些方法对我都适用
这是我对Swift 4的解决方案:
let monday = Day(name: "M")
let tuesday = Day(name: "T")
let friday = Day(name: "F")
let days = [monday, tuesday, friday]
let index = days.index(where: {
//important to test with === to be sure it's the same object reference
$0 === tuesday
})
其他回答
在Swift 2 (Xcode 7)中,Array包含了一个由CollectionType协议提供的indexOf方法。(实际上,有两个indexOf方法——一个使用相等来匹配参数,另一个使用闭包。)
在Swift 2之前,泛型类型(如集合)无法为从它们派生的具体类型(如数组)提供方法。所以,在Swift 1中。X, index of是一个全局函数…它也被重新命名了,所以在Swift 1中。X,这个全局函数叫做find。
这也是可能的(但不是必要的)使用indexOfObject方法从NSArray…或者其他任何来自基金会的更复杂的搜索方法,这些方法在Swift标准库中没有等价物。只需导入Foundation(或另一个传递导入Foundation的模块),将数组转换为NSArray,就可以使用NSArray上的许多搜索方法。
斯威夫特4
假设你想从名为cardButtons的数组中存储一个数字到cardNumber中,你可以这样做:
let cardNumber = cardButtons.index(of: sender)
Sender是按钮的名称
在Swift 4/5中,使用“firstIndex”查找索引。
let index = array.firstIndex{$0 == value}
你可以用闭包来过滤数组:
var myList = [1, 2, 3, 4]
var filtered = myList.filter { $0 == 3 } // <= returns [3]
你可以对数组进行计数:
filtered.count // <= returns 1
所以你可以通过组合这些来确定数组是否包含你的元素:
myList.filter { $0 == 3 }.count > 0 // <= returns true if the array includes 3
如果你想找这个职位,我不认为有什么花哨的方法,但你可以这样做:
var found: Int? // <= will hold the index if it was found, or else will be nil
for i in (0..x.count) {
if x[i] == 3 {
found = i
}
}
EDIT
当我们这样做的时候,为了一个有趣的练习,让我们扩展Array来有一个find方法:
extension Array {
func find(includedElement: T -> Bool) -> Int? {
for (idx, element) in enumerate(self) {
if includedElement(element) {
return idx
}
}
return nil
}
}
现在我们可以这样做:
myList.find { $0 == 3 }
// returns the index position of 3 or nil if not found
斯威夫特2.1
var array = ["0","1","2","3"]
if let index = array.indexOf("1") {
array.removeAtIndex(index)
}
print(array) // ["0","2","3"]
斯威夫特3
var array = ["0","1","2","3"]
if let index = array.index(of: "1") {
array.remove(at: index)
}
array.remove(at: 1)