【问题标题】:indexOf using with arrays in Swift [duplicate]indexOf 在 Swift 中与数组一起使用 [重复]
【发布时间】:2016-07-04 16:21:22
【问题描述】:

我有一个数组:

var swiftBlogs:[Message] = [Message]()

我想找到某个对象的索引号。我尝试了以下代码:

let mm=Message()
swiftBlogs.indexOf(mm)

但我收到编译器错误:

Cannot convert value of type 'Message' to expected argument type '@noescape (Message) throws -> Bool'

我该如何解决这个问题?

【问题讨论】:

  • Message 是什么?是Equatable吗?
  • 这是一个简单的类
  • 哪个版本的 Swift?
  • 我不知道号码,但 xcode 已更新到最新版本。所以>2.0

标签: swift


【解决方案1】:
class Message {
    var id: Int
    init(id: Int) {
        self.id = id
    }
}

var arr: [Message] = []
arr.append(Message(id: 1))
arr.append(Message(id: 2))
arr.append(Message(id: 3))
print(arr.indexOf { $0.id == 2 }) // Optional(1)

检查声明!!

.indexOf(predicate: (Message) throws -> Bool)

【讨论】:

    【解决方案2】:

    对于 Swift 3,它是:

    myArray.index{$0 === myMessage}
    

    它返回一个 Optional。

    【讨论】:

    • 详细说明你的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多