【问题标题】:Is encoding swift array of optionals possible?是否可以编码快速的选项数组?
【发布时间】:2015-09-22 10:38:49
【问题描述】:

我希望能够使用一组可选值对类进行编码。 Xcode 错误“无法使用类型为 '([SKSpriteNode?], for key: String') 的参数列表调用 'encode object'。

 class MyCustomNode: SKNode {

     var possibleSprites:[SKSpriteNode?] = [nil, nil, nil, nil, nil, nil, nil]

 ...

 }

override func encodeWithCoder(aCoder: NSCoder) {

    aCoder.encodeObject(self.possibleSprites, forKey: "POSSIBLESPRITES")
    super.encodeWithCoder(aCoder)

}

这有可能实现吗?如果没有,还有什么其他选择?


关于正确解码的问题...

以下,

 let x:[AnyObject!] = aDecoder.decodeObjectForKey("POSSIBLESPRITES") as! [AnyObject]
 self.possibleSprites = x.map { $0 == NSNull() ? nil : $0 }

我收到 Xcode 错误:“无法使用 '((_) -> _)' 类型的参数列表调用 'map'”

我相信它与返回类型有关,但不知道如何解决......

【问题讨论】:

  • 如何 var a:[AnyObject] = [NSNull(),NSNull()]

标签: arrays swift encode optional


【解决方案1】:

使用 Objective-C 你也不能编码一个 nil 指针。您需要将self.possibleSprites 映射到AnyObject? 的数组并使用NSNull 代替nil。

let x : [AnyObject!] = self.possibleSprites.map { $0 == nil ? NSNull() : $0 }
aCoder.encodeObject(x, forKey: "POSSIBLESPRITES")

记得在回来的路上正确解码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多