swift init可选数组包装

时间:2015-09-24 19:28:45

标签: ios iphone swift alamofire

嗨,我是swift的新手我想要一个可选的Array,有时候是null,我不知道什么是正确的语法,这里是代码

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
}

有时孩子可能是零,但是当它为空时会崩溃。

1 个答案:

答案 0 :(得分:1)

self.children = Content.collection(response:response, representation: representation.valueForKeyPath("children")!)

使用!,因为您强制可选展开..所以如果“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")
    }
}

替换&lt;“ClassType”&gt;通过正确的班级类型。