Search code examples
urlswift3foundationcustomstringconvertible

Override URL description


Originally I tried to use something like this:

extension URL: CustomStringConvertible{

    public override var description: String {
        let url = self

        return url.path.removingPercentEncoding ?? ""
    }
}

After fixing compiler warning code became:

extension URL{

    public var description: String {
        let url = self

        return url.path.removingPercentEncoding ?? ""
    }
}

but

print(fileURL) still shows old URL description with percentages.


Solution

  • You can't override a method in an extension. What you're trying to do isn't possible in Swift. It's possible in ObjC (on NSURL) by swizzling the methods, but this should never be done in production code. Even if you could get the above working in Swift through some trickery, you should never use that in production code for the same reason. It could easily impact you in very surprising ways (for instance, it could break NSCoding implementations that expect description to work a certain way.

    If you want this style of string, create a method for it and call that when you want it. Don't modify description in an existing class.