When looking at Apple ’s official Swift Language, I encountered an experiment: Write an extension for the Double type that add an absoluteValue property. When adding properties directly using extension, an error occurred (of course, the code has not been written yet, PlayGround It is easy to use).
extension Double {// add absoluteValue property to Double type by using extension.
var absoluteValue: Double {
}
}
The result is an error, saying: ‘var’ declaration without getter / setter method not allowed here
@Author: Twlkyao reprint or quote please keep this line.
According to the cause of the error, add getter and setter methods to solve this problem perfectly.
extension Double {// add absoluteValue property to Double type by using extension.
var absoluteValue: Double {
get {// the get could be omitted.
if self> 0 {
return self
} else {
return -self
}
}
}
}
var doubleNum = -2.2
doubleNum.absoluteValue
Note: extensionkeyword can add calculation attributes (instance attributes or class attributes) to the structure or class, and also enable the structure or class to adopt a specific protocol.
Swift-(1) Add properties to Swift built-in types