简体   繁体   English

快速初始化可选数组包装

[英]swift init optional array wrapping

Hi I'm new in swift I'm trying to have an Array that is optional, some times that is null, I don't know what is the proper syntax, here is the code 嗨,我是新手,我正在尝试使用一个可选的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
}

Children can be nil sometimes, but it crash when is null. 有时孩子可能为零,但是当为null时,它会崩溃。

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

With the ! ! , because you are forcing optional unwrapping.. so if "children" path does not exist, the app will crash. ,因为您要强制进行可选的展开操作。因此,如果“子级”路径不存在,则应用程序将崩溃。

UPDATE: 更新:

The signature for valueForKeyPath(_:) is: valueForKeyPath(_:)的签名为:

func valueForKeyPath(_ keyPath: String) -> AnyObject?

which returns an optional. 返回一个可选的。 I would suggest you to do: 我建议您这样做:

@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")
    }
}

replace <"ClassType"> by the correct class type. 用正确的类类型替换<“ ClassType”>。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM