Swift'AnyObject'没有名为“make”的成员

时间:2014-08-09 22:10:05

标签: object compiler-errors swift

我很困惑我如何将两个键作为字符串而一个工作而另一个不工作。在接近结尾的行中发生错误:

println(“这是(car.year)(car.make)(car.model)”)

可能导致问题的“make”变量是什么?

protocol NSCoding {

}

class Car:NSObject {

    var year: Int = 0
    var make: String = ""
    var model: String = ""

    override init() {
        super.init()
    }

    func encodeWithCoder(aCoder: NSCoder!) {
        aCoder.encodeInteger(year, forKey:"year")
        aCoder.encodeObject(make, forKey:"make")
        aCoder.encodeObject(model, forKey:"model")
    }

    init(coder aDecoder: NSCoder!) {

        super.init()

        year = aDecoder.decodeIntegerForKey("year")
        make = aDecoder.decodeObjectForKey("make") as String
        model = aDecoder.decodeObjectForKey("model") as String

    }
}

class CarData {


    func archiveData () {
        var documentDirectories:NSArray
        var documentDirectory:String
        var path:String
        var unarchivedCars:NSArray
        var allCars:NSArray

        // Create a filepath for archiving.
        documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)

        // Get document directory from that list
        documentDirectory = documentDirectories.objectAtIndex(0) as String

        // append with the .archive file name
        path = documentDirectory.stringByAppendingPathComponent("swift_archiver_demo.archive")

        var car1:Car! = Car()
        var car2:Car! = Car()
        var car3:Car! = Car()

        car1.year = 1957
        car1.make = "Chevrolet"
        car1.model = "Bel Air"

        car2.year = 1964
        car2.make = "Dodge"
        car2.model = "Polara"

        car3.year = 1972
        car3.make = "Plymouth"
        car3.model = "Fury"

        allCars = [car1, car2, car3]

        // The 'archiveRootObject:toFile' returns a bool indicating
        // whether or not the operation was successful. We can use that to log a message.
        if NSKeyedArchiver.archiveRootObject(allCars, toFile: path) {
            println("Success writing to file!")
        } else {
            println("Unable to write to file!")
        }

        // Now lets unarchive the data and put it into a different array to verify
        // that this all works. Unarchive the objects and put them in a new array
        unarchivedCars = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as NSArray

        // Output the new array
        for car : AnyObject in unarchivedCars {
            println("Here's a \(car.year) \(car.make) \(car.model)")
        }
    }

}

1 个答案:

答案 0 :(得分:1)

在for循环中使用向下转换。编译器需要知道汽车是Car类型,而不仅仅是AnyObject。

for car in cars as [Car!] {
    println("Here's a \(car.year) \(car.make) \(car.model)")
}