0

I'm writing an extension to String to return a reversed version of it:

extension String{

    func rev()->String{
        var r = ""
        r.extend(reverse(self))
        return r
    }
}

The code works fine, but I'd like to call this method reverse, and not rev. If I do it, I get an error as the method name conflicts with the generic function reverse:

extension String{

    func reverse()->String{
        var r = ""
        r.extend(reverse(self)) // this is where I get the error
        return r
    }
}

Is there a way to specify that I mean the generic function reverse inside the body of the method?

cfischer
  • 24,452
  • 37
  • 131
  • 214

1 Answers1

4

You can always call the Swift function explicitly by prepending the module name, e.g. Swift.reverse():

extension String{

    func reverse()->String{
        var r = ""
        r.extend(Swift.reverse(self))
        return r
    }
}

Note that you can simplify the function slightly to

func reverse()->String{
    return String(Swift.reverse(self))
}

This works because Swift.reverse() returns an array, Array conforms to SequenceType, and String has a constructor

init<S : SequenceType where Character == Character>(_ characters: S)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • You just beat me in posting, but yes this is correct. Use the `Swift` namespace to unambiguously access the Swift Standard Library. – nickgraef Nov 07 '14 at 16:18