【问题标题】:Checking index of element error [duplicate]检查元素错误的索引[重复]
【发布时间】:2018-04-13 15:44:50
【问题描述】:

我想检查数组中元素的索引:

var arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
print(arr.index(of: 2))

但我得到一个错误:

error: cannot invoke 'index' with an argument list of type '(of: Any)'
note: expected an argument list of type '(of: Self.Element)'

为什么控制台会抛出这个问题以及如何解决它?

【问题讨论】:

  • 要使用index(of:)必须采用Equatable协议。
  • 尽量避免这样的异构数组。与他们一起工作是一个巨大的痛苦。
  • 哈我想知道使用这种类型的数组是否“可以接受”,但现在我知道它不是。感谢您的建议:)

标签: arrays swift indexof any


【解决方案1】:

为了使用index(of:)必须采用Equatable协议

试试这个代码

   var arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
        print(arr.index(where: { (item) -> Bool in
            (item as? Int ) == 2
        }))

【讨论】:

  • 请注意,结果将是可选 :)
  • 你可以根据自己的需要使用if let,guard
【解决方案2】:

在异构数组中,您必须使用index(where API 并检查元素的类型:

let arr: [Any] = ["st","er","gh", 2, 5,"jk", 78 ]
if let index = arr.index(where: { $0 as? Int == 2 }) {
   print(index)
}

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2021-08-23
    • 2019-12-31
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多