Swift 3 数组 indexOf 函数丢失。

4
当我尝试打印包含任何对象的数组的索引时,它没有建议使用indexOf函数。当我尝试手动输入时,它显示错误,我已附上截图。

但对于字符串数组,它可以正常工作。有人能帮我解决这个问题吗?

enter image description here

这里我展示了我的代码

import UIKit

class ViewController: UIViewController {

    var arrayOfAnyObject: [Any] = [Any]()
    var arrayOfStringObject: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()


         print("Index of string object array \(arrayOfStringObject.index(of: "anyString")!)")

         print("Index of any object array \(arrayOfAnyObject.index(of: "anyObject")!)")




        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

你需要提到数组类型 var arrayOfAnyObject: [Int] = [Int]() - Anbu.Karthik
@Anbu.Karthik,使用“Any”数据类型无法正常工作。 - Mani murugan
你需要声明为 AnyObject 以进行类型转换。 - Anbu.Karthik
1个回答

4

您可以在数组中设置所需的类型(IntString等),或在执行indexOf之前将arrayOfAnyObject转换为AnyObject,例如:

print("Index of any object array \((arrayOfAnyObject as AnyObject).index(of: "anyObject"))")

谢谢Rashwan。它正常工作了。你能告诉我为什么它不显示indexOf函数而不需要转换吗?反正它是一个数组对吧? - Mani murugan
1
@Manimurugan,太好了。它不起作用是因为Any不符合可比协议。在此处阅读更多信息:(https://developer.apple.com/documentation/swift/equatable)。 - Rashwan L
@Manimurugan.mine在这里不起作用。为什么 :( 我只是按照Rashwan的建议更改了我的数据类型为AnyObject。像这样 var arrayOfAnyObject:[AnyObject] = AnyObject - elk_cloner
1
@elk_cloner,保持你的数组为 Any,当你使用 indexOf 时,请使用我提供的示例。 - Rashwan L

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接