Search code examples
swiftcomputed-properties

Write a computed property for Int . Swift


I want to write a computed property for Int. How can I refer to the current Int value?

extension Int {
    
    var asString: String {
        get {
          // <--
        }
    }
    
}

I don't understand how to refer to the current value.

NOTE: I know there is a "description". I want to understand how to implement this myself


Solution

  • You need to use self.

    extension Int {
        var currentValueString: String {
            String(self)
        }
    }
    

    Unrelated to your question, but why is the property optional? You can always convert an Int to a String, so it doesn't need to be optional.