类型'Type'的值没有下标Error Swift [英] Value of type 'Type' has no subscripts Error Swift
问题描述
尝试按字母顺序按名称"对数组中的JSON对象数组进行排序.给出错误消息类型为'IndividualContact'的值没有下标"不确定这是什么意思.感谢您的帮助.
Trying to sort the array of JSON objects in the array by "name" alphabetically. Gives error of "Value of type 'IndividualContact' has no subscripts" Not sure what that means. Any help is appreciated.
class Contacts{
var contact = [IndividualContact]()
init?(data2: Data) {
do {
if let json2 = try JSONSerialization.jsonObject(with: data2) as? [String: Any], let body = json2["data2"] as? [String: Any] {
if let contacts = body["contacts"] as? [[String: Any]] {
self.contact = ( contacts.map { IndividualContact(json2: $0) } )
}
}
contact.sorted(by: { ($0["name"] as! String) < ($1["name"] as! String) })
} catch {
print("Error deserializing JSON: \(error)")
return nil
}
}
}
推荐答案
编译器告诉您,对象(IndividualContact
)没有提供下标标记(即[...]
)的实现.尽管您可以在struct/class中提供该实现,但是在这种情况下这样做可能会过大.您可能只想在sorted(by:)
闭包中调用$0.name
:
The compiler is telling you that your object (IndividualContact
) doesn't provide an implementation for the subscript token, i.e. [...]
. While you could provide that implementation in your struct/class, doing so might be overkill in this situation. You probably just want to call $0.name
in your sorted(by:)
closure:
contact.sorted(by: { $0.name < $1.name })
如果您确实想使用$0["name"]
语法,则可以提供这样的实现.它可能看起来像这样:
If you really do want to use the $0["name"]
syntax, then you can provide such an implementation. It might look something like this:
subscript(key: String) -> String {
get {
switch key {
case "name":
return self.name
default:
return ""
}
}
set {
...
}
}
有关下标的更多信息,请参见: https://docs. swift.org/swift-book/LanguageGuide/Subscripts.html
More info on subscripts can be found here: https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html
这篇关于类型'Type'的值没有下标Error Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!