0

I am new to Swift 2. Being learning extension, which I found it is pretty cool feature compared with OC.

An example from apple developer: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

extension Int {
    mutating func square() {
        self = self * self
    }
}
var someInt = 3
someInt.square()
// someInt is now 9

So I was thinking, is it possible to have extension to return value like this:

extension Int {
    func square() {
        return self * self
    }
}
var someInt = 3
someInt.square()
//ERROR: error: no '*' candidates produce the expected contextual result type '()'

My question is how to return a value within an extension? Thanks

Ben
  • 946
  • 1
  • 11
  • 19

1 Answers1

4

Just like with any other function, you'd need to specify the return type.

extension Int {
    func squared() -> Int {
        return self * self
    }
}
let someInt = 3
let square = someInt.squared()
Thilo
  • 257,207
  • 101
  • 511
  • 656