错误用swift中的类实例填充数组

时间:2015-12-03 21:46:26

标签: arrays swift object

使用Swift我正在尝试创建一个充满对象的数组。我一直得到这个错误实例成员joe(第一个值)不能用于类型' Friend'(该类)

然后我想打印每个对象的name值。这是我的代码。

import UIKit

class Friend {

    var name:String = "aName"
    var athletic = 0
    var brains = 0
    var male:Bool = false

    init (name:String, brains:Int, athletic:Int, male:Bool){
        self.name=name
        self.athletic=athletic
        self.brains=brains
        self.male=male
    }

    let joe = Friend(name: "Joe", brains: 2, athletic: 3, male: true)
    let dave = Friend(name: "Dave", brains: 4, athletic: 4, male: true)
    let brent = Friend(name: "Bent", brains: 5, athletic: 1, male: true)
    let logan = Friend(name: "Logan", brains: 1, athletic: 5, male: true)

    var allFriends: [Friend] = [joe, dave, brent, logan]  //this is where the error occurs.

    for i in allFriends {
        print allFriends[i].name
    }
}

请帮助谢谢:)

1 个答案:

答案 0 :(得分:0)

你缺少一个结束括号:

class Friend {

    var name:String = "aName"
    var athletic = 0
    var brains = 0
    var male:Bool = false

    init (name: String, brains: Int, athletic: Int, male: Bool){
        self.name=name
        self.athletic=athletic
        self.brains=brains
        self.male=male
    } // THIS IS THE MISSING BRACE
}

let joe = Friend(name: "Joe", brains: 2, athletic: 3, male: true)
let dave = Friend(name: "Dave", brains: 4, athletic: 4, male: true)
let brent = Friend(name: "Bent", brains: 5, athletic: 1, male: true)
let logan = Friend(name: "Logan", brains: 1, athletic: 5, male: true)

var allFriends = [joe, dave, brent, logan]  //this is where the error occurs.

for i in allFriends {
    print(i.name)
}