Reputation: 553
I know that probably is a very simple question, however I spent a lot of time trying to figure out why is not working, and still doesn't make sense for me, so I need help.
I am learning iOS, I came from Android where I am used to work with objects. I want to do something similar that I have been doing with Android(maybe this is the problem).
I have created an object with the methods get and set.
private var _token: String!
var error: String {
get {
guard self._error != nil else { return "" }
return _error
}
set {
self._token = newValue
}
}
When I want to manipulate this object, is when I am having the problem.
let objectCreated = ObjectCreated()
guard let errorReceived = (xml["Whatever"]["Whatever"].element?.text) else { return }
print(errorReceived)
objectCreated.error = errorReceived
print(objectCreated.error)
The first print is printing the correct String, but the second is printing "". So the set method is not doing his job.
Upvotes: 0
Views: 226
Reputation: 285092
Isn't it supposed to be
...
guard self._token != nil else { return "" }
return _token
...
This can be simplified with the nil-coalescing operator
var error: String {
get {
return self._token ?? ""
}
set {
self._token = newValue
}
}
Note: Variable names with leading underscores are unusual in Swift.
Upvotes: 2
Reputation: 27211
private var _error: String!
var error: String {
get {
guard self._error != nil else { return "" }
return _error
}
set {
self._error = newValue
}
}
self._token = newValue >>>> self._error
= newValue
Upvotes: 1