![](/img/trans.png)
[英]Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String'
[英]Cannot subscript a value of type '[NSObject : AnyObject]?' with an index of type 'String' Swift Error
我的鱈魚就是那個,這個錯誤出現在課程的最后一行,我該怎么做才能解決呢?
public class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces) {
let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, to: AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)" as CFString)
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData?["SSID"] as String
}
}
}
return currentSSID
}
}
使用下標的唯一行是:
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData?["SSID"] as String
使用這樣的字符串進行訪問: interfaceData?["SSID"]
要求您以不同的方式定義字典,當前字典被聲明為[NSObject: AnyObject]
但要使用String下標,則必須為[String: AnyObject]
嘗試將此行更改為:
let interfaceData = unsafeInterfaceData! as [String: AnyObject]
注意:如果讓用而不是用!
強制展開,則最好使用!
你可以試試
if let interfaceData = unsafeInterfaceData! as? [String:Any]
{
currentSSID = interfaceData["SSID"] as? String
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.