arrays - 如何获取数组中元素的位置

标签 arrays swift

我有一个问题,希望你们中的一个人能帮助我:我需要找到数组中元素的位置。 例如:

var elements: [String] = ["a","b","c","a","c"]
var element = "a"

我需要知道元素在什么位置,在本例中为0,3 我尝试过一些嵌套的 for 循环,但很困惑,你能帮我吗? 谢谢

最佳答案

试试这个:

var elements: [String] = ["a","b","c","a","c"]
var element = "a"
let indexes = elements.enumerated().compactMap { index, elem -> Int? in
  guard elem == element else { return nil }
  return index
}
print(indexes) // It will print [0, 3]

关于arrays - 如何获取数组中元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55090030/

相关文章:

c - 多维数组的某些元素错误地读为零

ios - UIWebView 中嵌入的 Youtube 视频在真实设备上没有声音

xcode - 为什么我的 scrollView 是零?

c++ - 在不先构建数组的情况下将数字列表传递给 C++ 中的函数?

javascript - Array.push throw TypeError for array.push is not a function

c# - 在 VB NET 或 C# 中发布 PHP 数组

php - 需要帮助来修复我使用对象代码创建的多维数组

ios - 寻找 cocoa 模块的框架

ios - UICollectioviewCell 中的 Uiview 的左下角和右下角半径问题

ios - 无法通过 'pod install' 命令安装库