ios - swift init 可选的数组包装

标签 ios iphone swift alamofire

嗨,我是 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/

相关文章:

iphone - 如何在两个 UIButton 选择器之间切换

ios - 保护 iPhone 应用程序的数据馈送

arrays - 可比较的扩展有效但结果不佳

swift - 如何指定输出可执行文件的名称?

ios - 如何更改 SceneKit 中枢轴点的位置

ios - 向上滚动时 UITableView 有延迟

ios - 我在 iTunes 连接中的构建选项旁边没有看到 '+' 按钮?

ios - 尝试访问 Swift 中的无主引用总是导致应用程序崩溃

iphone - 自定义 UIButton 的发光效果,如信息 UIButton

基于 iPhone View 的应用程序没有核心数据?