本文介绍了如何在 Swift 中找到列表项的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过搜索 list 来查找 item index.有人知道怎么做吗?

I am trying to find an item index by searching a list. Does anybody know how to do that?

我看到有 list.StartIndexlist.EndIndex 但我想要类似 python 的 list.index("text") 的东西.

I see there is list.StartIndex and list.EndIndex but I want something like python's list.index("text").

推荐答案

由于 swift 在某些方面比面向对象更具有功能性(并且数组是结构,而不是对象),因此请使用函数find";对数组进行操作,它返回一个可选值,所以准备处理一个 nil 值:

As swift is in some regards more functional than object-oriented (and Arrays are structs, not objects), use the function "find" to operate on the array, which returns an optional value, so be prepared to handle a nil value:

let arr:Array = ["a","b","c"]
find(arr, "c")!              // 2
find(arr, "d")               // nil

使用 firstIndexlastIndex - 取决于您要查找项目的第一个索引还是最后一个索引:

Use firstIndex and lastIndex - depending on whether you are looking for the first or last index of the item:

let arr = ["a","b","c","a"]

let indexOfA = arr.firstIndex(of: "a") // 0
let indexOfB = arr.lastIndex(of: "a") // 3

这篇关于如何在 Swift 中找到列表项的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 07:27