Type Has No Subscript Members?

Mr_CryptoPrime picture Mr_CryptoPrime · Mar 21, 2016 · Viewed 39.6k times · Source

I get the error "Type 'Ship' has no subscript members when I try to do:

var coor = ship[index]

I tried to do

var coor = ship?[index] as? Coordinate

But I get this error: "Cannot use optional chaining on non-optional value of type 'Ship'"

Here's my Ship class:

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")
    }
}

The Coordinate class is also of type NSObject, NSCoding, etc... The objects seem to be in the array when I load them (from NSUserDefaults)? How do I get them out?!

Answer

JAL picture JAL · Mar 21, 2016

Add a subscript to your Ship object to return an optional Coordinate:

subscript(index: Int) -> Coordinate? {
    guard let coordinate = shipCoors?[index] else {
        return nil
    }
    return coordinate
}

shipCoors is declared as [Coordinate]? (an optional array), so there's a risk a Ship won't have an array in shipCoors. In this case I return nil, but you can return whatever you want instead.