Instance member cannot be use on type

帅比萌擦擦* 提交于 2021-01-29 04:03:59

问题


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

Above is the function I am trying to implement and below is the class I am trying to create an instance of and store the data from my text fields in... I am getting the error "Instance member "firstName" cannot be used on type Person". I was almost positive that my class was setup and initialised properly so I can't see what the problem could be?

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
    }

}

回答1:


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
}



回答2:


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



回答3:


"Instance member "firstName" cannot be used on type Person" is perfect explanation.

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'


来源:https://stackoverflow.com/questions/36472475/instance-member-cannot-be-use-on-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!