2017-06-08 48 views
3

當我嘗試打印包含任何對象的數組的索引。它並不暗示indexOf函數。當我嘗試手動輸入其附加屏幕截圖的顯示錯誤時。Swift 3 array 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. 
    } 


} 
+0

你需要提及數組類型' var arrayOfAnyObject:[Int] = [Int]()' –

+0

@ Anbu.Karthik它不能與「任何」數據類型 –

+0

一起使用,因此您需要將Decalre作爲AnyObject進行類型轉換 –

回答

4

您既可以設置你的陣列(IntString等)中所需要的類型或之前轉換arrayOfAnyObjectAnyObject你做indexOf,像這樣:

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

謝謝Rashwan。它的工作。你能告訴我爲什麼它沒有顯示indexOF功能沒有轉換。無論如何,它的數組是正確的? –

+1

@Manimurugan,太棒了。它不工作,因爲「任何」不能確認等價協議。閱讀更多[這裏](https://developer.apple.com/documentation/swift/equatable)。 –

+0

@Manimurugan.mine不在這裏工作。爲什麼:(我只是改變了我的數據類型爲AnyObject Rashwan建議的類似 var arrayOfAnyObject:[AnyObject] = [AnyObject]() –