gpt4 book ai didi

swift - 无法将类型 'Swift.Array<(Swift.String, Swift.String)>' 的值转换为 'Swift.AnyObject'

转载 作者:行者123 更新时间:2023-11-28 06:49:56 29 4
gpt4 key购买 nike

我的 swift 代码如下所示

Family.arrayTuple:[(String,String)]? = []
Family.arrayTupleStorage:String?
Family.arrayTupleStorage:String = (newDir! as NSString).stringByAppendingPathComponent("arrayTuple.archive")
NSKeyedArchiver.archiveRootObject(Family.arrayTuple! as! AnyObject, toFile: Family.arrayTupleStorage!)

我在构建代码时在控制台窗口中有错误消息。

'Could not cast value of type 'Swift.Array<(Swift.String, Swift.String)>' (0xcce8098) to 'Swift.AnyObject' (0xcc8f00c).'

如何存档 Family.arrayTuple 和取消存档 Family.arrayTupleStorage

最佳答案

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

let obj = SomeClass()
obj.foo = (6,5)

let data = NSKeyedArchiver.archivedDataWithRootObject(obj)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "books")

if let data = NSUserDefaults.standardUserDefaults().objectForKey("books") as? NSData {
let o = NSKeyedUnarchiver.unarchiveObjectWithData(data) as SomeClass
println(o.foo) // (Optional(6), Optional(5))

}
}
}

class SomeClass: NSObject, NSCoding {
var foo: (x: Int?, y: Int?)!

required convenience init(coder decoder: NSCoder) {
self.init()
let x = decoder.decodeObjectForKey("myTupleX") as Int?
let y = decoder.decodeObjectForKey("myTupleY") as Int?
foo = (x,y)
}

func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(foo.x, forKey: "myTupleX")
coder.encodeObject(foo.y, forKey: "myTupleY")
}
}

关于swift - 无法将类型 'Swift.Array<(Swift.String, Swift.String)>' 的值转换为 'Swift.AnyObject',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35200717/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com