Hi,
I can create stored properties for eg lastName, firstName.
var lastName: String
var firstName: String
...
But what in case if I want eg:
- if I want to have the possibility to change the lastName and/or firstName during the lifecycle of the object.
- test if the passed value for lastName and/or firstName is empty or not
What is the way to do this in Swift?
Thanks.
Guy
Your code converted to Swift:
public class Person {
private var _id: Int = 0
private var _lastName: String = ""
public init(id: Int, lastName: String) {
self.id = id
self.lastName = lastName
}
public var id: Int {
get {
return self._id;
}
set {
if newValue < 0 || newValue > 1000 {
// Swift setter cannot throw error.
fatalError("invalid value for id")
} else {
self._id = newValue
}
}
}
public var lastName: String {
get {
return self._lastName
}
set {
// In Swift, non-optional String can never get nil.
if newValue.isEmpty {
fatalError("invalid value for lastName")
} else {
self._lastName = newValue
}
}
}
}
I believe this code fulfills your demand:
This code let's you test 1) if the passed in values are correct and 2) give the possibility to change a value when needed.
You may need to reconstruct your error handling strategy in Swift, but defining properties does not seem to be different.