【问题标题】:swift init optional array wrappingswift init 可选数组包装
【发布时间】:2015-09-24 19:28:44
【问题描述】:

您好,我是 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 时会崩溃。

【问题讨论】:

    标签: ios iphone swift alamofire


    【解决方案1】:
    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")
        }
    }
    

    将 替换为正确的类类型。

    【讨论】:

    • 是的,我希望属性 children 是可选的,有时是 nil,我该怎么做??
    • 这不起作用,因为在 init 方法中,我只是尝试一下,我得到编译器错误消息
    • Content.swift:24:27: 变量“self.children”在初始化之前使用
    • 你没有调用 super.init
    • 没有。我也尝试了您更新的最后一个,如果 var 处于内部状态,则出现同样的问题,我会收到该错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2015-12-04
    • 1970-01-01
    相关资源
    最近更新 更多