swiftnamespacesname-clashname-collision

Namespaces in Swift


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?


Solution

  • 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)