ArrayLiteralConvertible: Just a normal protocol?

醉酒当歌 提交于 2019-12-23 17:18:55

问题


Trying to understand and appreciate how ArrayLiteralConvertible works...

struct Struct<T>: ArrayLiteralConvertible {

    init(arrayLiteral elements: T...) {
        for element in elements {
            print(element)
        }
    }
}

let str: Struct<Int> = [1,2,3]

Output:

1
2
3

Now I am trying to do the same thing but this time with my own version of ArrayLiteralConvertible:

protocol MyALC {
    typealias Element
    init(arrLit elements: Self.Element...)
}

struct NewStruct<T>: MyALC {

    init(arrLit elements: T...) {
        for element in elements {
            print(element)
        }
    }
}

let newStr: NewStruct<Int> = [1,2,3]

However it does not work!

error: cannot convert value of type '[Int]' to specified type 'NewStruct'
let newStr: NewStruct = [1,2,3]

Am I doing something wrong or is there a special handling for ArrayLiteralConvertible?


回答1:


Generally, literals are a purely compile-time artifact. They can be used to produce an object initialized from that literal, but once the compilation phase is over, nobody knows that something was a literal.

This suggests that any support for the protocols below needs to be built into the compiler itself:

  • ArrayLiteralConvertible
  • BooleanLiteralConvertible
  • DictionaryLiteralConvertible
  • ExtendedGraphemeClusterLiteralConvertible
  • FloatLiteralConvertible
  • NilLiteralConvertible
  • IntegerLiteralConvertible
  • StringLiteralConvertible
  • StringInterpolationConvertible
  • UnicodeScalarLiteralConvertible

The compiler would not take your own protocol as a replacement of any of the above.



来源:https://stackoverflow.com/questions/32502727/arrayliteralconvertible-just-a-normal-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!