Define an extension with the property.
here is an example, with 2 properties:
extension Int {
var doubleIt: Int {
return self * 2
}
var asString: String {
return String(self)
}
}
print(1.doubleIt, 1.asString)
yields
2 1
You have an interesting example in Swift language book in Trailing Closures paragraph to
« use the map(_:) method with a trailing closure to convert an array of Int values into an array of String values. The array [16, 58, 510] is used to create the new array ["OneSix", "FiveEight", "FiveOneZero"]: »
Extrait de: Apple Inc. « The Swift Programming Language (Swift 4). » Apple Books.
So, inspired by this, you can write a spelled property:
extension Int {
var doubleIt: Int {
return self * 2
}
var asString: String {
return String(self)
}
var spelled: String {
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
var number = self > 0 ? self : -self
var output = ""
repeat {
output = digitNames[number % 10]! + (output == "" ? "": "-") + output
number /= 10
} while number > 0
if self < 0 { output = "minus " + output }
return output
}
}
print(1.doubleIt)
print(1.asString)
print((-1).spelled)
print(25.spelled)
will yield
2
1
minus One
Two-Five
You can play with it and refine so that 25 yields twenty five
In fact, number formatter does it:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .spellOut
let string = numberFormatter.string(from: -25) ?? ""
print(string)
yields
minus twenty-five