问题
@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