实例成员不能在类型上使用

时间:2016-04-07 09:47:44

标签: xcode swift swift2 xcode7

@IBAction func saveDetails(sender: AnyObject) {
        Person.firstName = firstNameTF.text
        Person.lastName = lastNameTF.text
}

上面是我正在尝试实现的功能,下面是我正在尝试创建一个实例并从我的文本字段中存储数据的类...我收到错误"实例成员&# 34;的firstName"不能用于Person"类型。我几乎是肯定的,我的课程设置正确,所以我无法看到问题是什么?

class Person {
    var firstName : String = ""
    var middleName : String? = nil
    var lastName : String = ""
    var yearOfBirth : Int? = nil
    var age : Int! {
        get {
            guard let _ = yearOfBirth else {
                return nil
            }
            return currentYear - yearOfBirth!
        }
        set {
            yearOfBirth = currentYear - newValue
        }
    }

    init(firstName: String, lastName: String, yearOfBirth: Int? = nil, middleName: String? = nil){
        self.firstName = firstName
        self.lastName = lastName
        self.yearOfBirth = yearOfBirth
        self.middleName = middleName
    }
    convenience init(firstName: String, lastName: String, age: Int, middleName: String? = nil) {
        self.init(firstName: firstName, lastName: lastName, yearOfBirth: nil, middleName: middleName)
        self.age = age
    }

}

3 个答案:

答案 0 :(得分:3)

The error message says you cannot call the properties on the class (type) Person.

Create a Person instance using the given initializer

@IBAction func saveDetails(sender: AnyObject) {
   let person = Person(firstName:firstNameTF.text, lastName:lastNameTF.text)
   // do something with person
}

答案 1 :(得分:1)

You should create an instance of Person in order to set its properties: either do this:

@IBAction func saveDetails(sender: AnyObject) {
    let p = Person(firstName: firstNameTF.text!, lastName: lastNameTF.text!)
}

or add an init method that doesn't take arguments to your Person class

@IBAction func saveDetails(sender: AnyObject) {
    let p = Person()
    p.firstName = firstNameTF.text!
    p.lastName = lastNameTF.text!
}

答案 2 :(得分:0)

“实例成员”firstName“不能在类型Person上使用”是完美的解释。

class C {
    var s: String = ""
    static var s1: String = ""
}


C.s1 = "alfa"
//C.s = "alfa" //  error: instance member 's' cannot be used on type 'C'
let c0 = C()
c0.s = "beta"
//c0.s1 = "beta" // error: static member 's1' cannot be used on instance of type 'C'