嗨,我是 swift 的新手,我试图有一个可选的数组,有时为空,我不知道正确的语法是什么,这是代码
public final class Content: ResponseObject,ResponseCollection {
public let created: String
public let name: String
public let children: [Content]?
@objc required public init?(response: NSHTTPURLResponse, representation: AnyObject) {
self.name = representation.valueForKeyPath("name") as! String
self.created = representation.valueForKeyPath("created") as! String
self.children = Content.collection(response:response, representation: representation.valueForKeyPath("children")!)
}
@objc public static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Content] {
var contents: [Content] = []
if let representation = representation as? [[String: AnyObject]] {
for contentRepresentation in representation {
if let content = Content(response: response, representation: contentRepresentation) {
contents.append(content)
}
}
}
return contents
}
children 有时可以为 nil,但当为 null 时会崩溃。
最佳答案
self.children = Content.collection(response:response, representation: representation.valueForKeyPath("children")!)
使用 !
,因为您强制执行可选的解包..所以如果“子”路径不存在,应用程序将崩溃。
更新:
valueForKeyPath(_:)
的签名是:
func valueForKeyPath(_ keyPath: String) -> AnyObject?
它返回一个可选的。我建议你这样做:
@objc required public init?(response: NSHTTPURLResponse, representation: AnyObject) {
if let namePath = representation.valueForKeyPath("name") as? String, createdPath = representation.valueForKeyPath("created") as? String, childrenPath = representation.valueForKeyPath("children") as? String {
self.name = namePath
self.created = createdPath
self.children = Content.collection(response:response, representation: childrenPath)
}
else {
println("name path, created path, or children path does not exists")
}
}
用正确的类类型替换 <"ClassType">。
关于ios - swift init 可选的数组包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32769421/