当我尝试这样做时,我收到错误“Type’Ship’没有下标成员:
var coor = ship[index]
我试着这样做
var coor = ship?[index] as? Coordinate
但我得到这个错误:“不能在’Ship’类型的非可选值上使用可选链接”
这是我的Ship类:
import Foundation class Ship: NSObject,NSCoding { var shipCoors: [Coordinate]? var count: Int { var count = 0 for _ in shipCoors! { count++ } return count } init(shipCoors: [Coordinate]) { self.shipCoors = shipCoors } required init(coder decoder: NSCoder) { self.shipCoors = decoder.decodeObjectForKey("shipCoors") as? [Coordinate] } func encodeWithCoder(coder: NSCoder) { coder.encodeObject(shipCoors,forKey: "shipCoors") } }
Coordinate类也是NSObject,NSCoding等类型……
加载它们时,对象似乎在数组中(来自NSUserDefaults)?我怎么把它们拿出去?!
解决方法
向Ship对象添加下标以返回可选的Coordinate:
subscript(index: Int) -> Coordinate? { guard let coordinate = shipCoors?[index] else { return nil } return coordinate }
shipCoors被声明为[Coordinate]? (一个可选的数组),因此Ship可能没有shipCoors中的数组.在这种情况下,我返回nil,但你可以返回你想要的任何东西.