Search code examples
arraysswiftswift3

Is there a way to override Array to String casting in Swift?


I'm playing around with Swift trying to make it look more "dynamically typed" – just for fun, no production value expected.

Now I'm stuck with overwriting behavior of converting builtin types to String.

For example, I'd like to see this output for Array:

let nums = [1, 2, 3]
print(nums) // "I'm an array"

So far I tried to

  • make an extension to NSArray (not compiles)
  • implement CustomStringConvertible (not compiles)
  • make an extension to Array (compiles, changes nothing)

Seems like I'm on the wrong path:

extension Array: CustomStringConvertible {
    public var description: String { return "An array" }
}

gives the warning:

Conformance of 'Array' to protocol 'CustomStringConvertible' was already stated in the type's module 'Swift'

Is this doable in Swift?


Solution

  • This does not work because Array overrides description. If array did not override it then it would print "An array". The class method 'wins' over the extension.

    extension Array {
        public var description: String { return "An array" }
    }
    

    You could create a Wrapper class for your array. It's a workaround but doesn't override array's description itself.

    class ArrayWrapper<T> : CustomStringConvertible{
        var array : Array<T> = Array<T>()
        var description: String { return "An array" }
    }
    

    You could then use it like this.

    var array = ArrayWrapper<Int>()
    array.array = [1,2,3]
    print(array) //prints "An Array"
    print(array.array) //still prints "[1, 2, 3]"