我在Obj-C中做了很多NSCoding归档,但是我不知道如何处理Swift中的结构体,也不知道如何处理Swift中的结构体,也不知道如何处理Swift中的结构体。这是我的代码:
@H_502_20@
我不知道确切的问题是什么,但如果您使用NSMutableArray而不是Swift数组,问题解决:
public struct SquareCoords { var x: Int,y: Int }
这里是我需要存储的课程:
public class Player: NSCoding { var playerNum: Int var name = "" private var moveHistory: [SquareCoords?] = [] init (playerNum: Int,name: String) { self.playerNum = playerNum self.name = name } public required init(coder aDecoder: NSCoder!) { playerNum = aDecoder.decodeIntegerForKey("playerNumKey") name = aDecoder.decodeObjectForKey("nameKey") as String moveHistory = aDecoder.decodeObjectForKey("moveHistoryKey") as [SquareCoords?] } public func encodeWithCoder(aCoder: NSCoder!) { aCoder.encodeInteger(playerNum,forKey: "playerNumKey") aCoder.encodeObject(name,forKey: "nameKey") aCoder.encodeObject(moveHistory,forKey: "moveHistoryKey") } ...
在编码器init的最后一行,我在XCode中收到以下错误消息:
'AnyObject' is not convertible to [SquareCoords?]'
并在编码的最后一行:
Extra argument 'forKey' in call
任何人都可以让我朝着正确的方向前进吗?
public struct SquareCoords { var x: Int,y: Int } public class Player: NSCoding { var playerNum: Int var name = "" var moveHistory: NSMutableArray = NSMutableArray() init (playerNum: Int,name: String) { self.playerNum = playerNum self.name = name } public required init(coder aDecoder: NSCoder!) { playerNum = aDecoder.decodeIntegerForKey("playerNumKey") name = aDecoder.decodeObjectForKey("nameKey") as String moveHistory = aDecoder.decodeObjectForKey("moveHistoryKey") as NSMutableArray } public func encodeWithCoder(aCoder: NSCoder!) { aCoder.encodeInteger(playerNum,forKey: "moveHistoryKey") } }
似乎是这样的情况,当aDecoder.decodeObjectForKey返回一个隐式解开的AnyObject时,它不会转换为一个SquareCoords数组。
玩了一点,我注意到它可能与使用结构有关。 (你正在创建一个值类型的结构体数组。)这是一个猜测,但是我注意到,如果一个类类型用于SquareCoords,那就没有问题,例如
public class SquareCoords { var x: Int = 0,y: Int = 0 } public class Player: NSCoding { var playerNum: Int var name = "" private var moveHistory: [SquareCoords] = [SquareCoords]() init (playerNum: Int,name: String) { self.playerNum = playerNum self.name = name } public required init(coder aDecoder: NSCoder!) { playerNum = aDecoder.decodeIntegerForKey("playerNumKey") name = aDecoder.decodeObjectForKey("nameKey") as String moveHistory = aDecoder.decodeObjectForKey("moveHistoryKey") as [SquareCoords] } public func encodeWithCoder(aCoder: NSCoder!) { aCoder.encodeInteger(playerNum,forKey: "playerNumKey") aCoder.encodeObject(name,forKey: "nameKey") aCoder.encodeObject(moveHistory,forKey: "moveHistoryKey") } }
也许由于某种原因,AnyObject的转换不会导致一个struct数组。 – 我相信别人可以提供更多的见解,希望这有所帮助!斯威夫特可以是暴风雨的:D