有没有办法在Swift中将Array覆盖为String

有没有办法在Swift中将Array覆盖为String

本文介绍了有没有办法在Swift中将Array覆盖为String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在和Swift一起玩,试图使其看起来更动态类型化" –只是为了娱乐,没有预期的生产价值.

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

现在,我陷入了将内置类型转换为String的覆盖行为.

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

例如,我想查看Array的输出:

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

  • NSArray进行扩展(不编译)
  • 实现CustomStringConvertible(不编译)
  • 扩展Array(编译,不做任何更改)
  • make an extension to NSArray (not compiles)
  • implement CustomStringConvertible (not compiles)
  • make an extension to Array (compiles, changes nothing)

好像我走错了路:

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

至少在Swift中可行吗?

Is it at least doable in Swift?

有什么想法吗?

推荐答案

这不起作用,因为Array覆盖了描述.如果数组未覆盖它,则它将打印数组".类方法胜过"扩展程序.

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" }
}

您可以为数组创建Wrapper类.这是一种解决方法,但不会覆盖数组本身的描述.

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]"

这篇关于有没有办法在Swift中将Array覆盖为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:25