在Swift中实现NSCoding?

在Swift中实现NSCoding?,swift,nscoding,Swift,Nscoding,我在这里实现了一个示例: 我在两条语句中得到错误“预期声明”: documentDirectories=NSSearchPathForDirectoriesInDomains(.DocumentDirectory、.UserDomainMask,true) 及 car1.1年=1957年 想法 class CarData { var documentDirectories:NSArray = [] var documentDirectory:String = "" v

我在这里实现了一个示例:

我在两条语句中得到错误“预期声明”:

documentDirectories=NSSearchPathForDirectoriesInDomains(.DocumentDirectory、.UserDomainMask,true)

car1.1年=1957年

想法

class CarData {

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

}

您正在类声明中编写代码! 声明第一组变量后的任何代码都需要在函数内部。例如
init()
函数