【问题标题】:index (of: element) does not exist索引(属于:元素)不存在
【发布时间】:2017-02-22 15:34:40
【问题描述】:

我有一个非常奇怪的错误。一直在学习 Swift,正在阅读有关在数组中查找对象索引的文档:https://developer.apple.com/reference/swift/array/1689674-index

但是这个方法在我的 Xcode 中不存在。

这是一个例子:

var items : [TaskItem]
items = [TaskItem] () 

    let rowitem = TaskItem()
    rowitem.text = "helloworld"
    items.append(rowitem)

//Attempting to find the index of an object

   items.Index(of: rowitem) 

//错误 - Xcode 找不到我正在寻找的特定函数

我附上了出现的方法的图像,但无法找到为什么这可能会在任何地方发生的答案。

我找不到 func index(of:) 方法的用途,虽然我知道它存在!

我收到以下编译器错误:

ChecklistViewController.swift:186:26: 参数标签 '(of:, _:)' do 不匹配任何可用的重载

ChecklistViewController.swift:186:26: 'index' 的重载存在于 这些部分匹配的参数列表:(Int, offsetBy: Int), (Self.Index, offsetBy: Self.IndexDistance)

【问题讨论】:

  • 这是您帖子中的错字吗?应该是items.index(of: rowitem)。注意index 而不是Index
  • TaskItem Equatable?

标签: swift indexof


【解决方案1】:

TaskItem 需要符合Equatable 协议才能使用index(of:)

【讨论】:

  • 如果是class,只需确保类继承自NSObject - 这是平等的。
【解决方案2】:

我完全同意 Tim vermeulen 的观点,但是我们可以使用下面的代码获取数组的索引,并且它工作得很好。

class Name {

    var firstName:String  = String()
    var lastName:String = String()

    var fullName:String{
        return firstName+lastName
    }
}

var items:[Name] = [Name]()

    let rowitem = Name()

    let name:Name = Name()
    name.firstName = "Vala"
    name.lastName = "bbbb"

    items.append(rowitem)
    items.append(name)

//Attempting to find the index of an object
   print(items.index{$0 === name}!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 2017-10-25
    • 1970-01-01
    • 2014-06-27
    • 2015-08-15
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    相关资源
    最近更新 更多