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

I play with Swift, trying to make it look more "dynamically typed" - just for fun, the expected production is not expected.

Now I'm stuck in rewriting the behavior of converting inline types to String.

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

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

So far i tried

  • make extension to NSArray(not compiled)
  • implement CustomStringConvertible(not compiled)
  • make an extension to Array(compiles, does not change anything)

It seems like I'm wrong:

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

How is this possible in Swift?

Any ideas?

+4
source share
2

, Array . , "". "" .

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

Wrapper . , .

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

.

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

, Array.

, ( @Yannick) ArrayLiteralConvertible, .

struct Array<T> {
    let array: [T]
}

extension Array: ArrayLiteralConvertible {
    init(arrayLiteral elements: T...) {
        self.array = elements
    }
}

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

let array = [1,2,3]
print(array) // "An array\n"
-1

Source: https://habr.com/ru/post/1651839/


All Articles