在swift中用类实例填充数组时出错



使用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
    }
}

请帮忙谢谢:)

您缺少一个右大括号:

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

最新更新