ArrayLiteralConvertible:只是一个正常的协议? [英] ArrayLiteralConvertible: Just a normal protocol?

查看:172
本文介绍了ArrayLiteralConvertible:只是一个正常的协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  struct Struct< T>:ArrayLiteralConvertible {

init(arrayLiteral元素:T ...){
元素元素{
print(element)
}
}
}

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

输出:

 
1
2
3

现在我正在尝试同样的事情,但这次用我自己的ArrayLiteralConvertible版本:

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

struct NewStruct< T> ;: MyALC {

init(arrLit elements:T ... ){
元素元素{
print(element)
}
}
}

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

然而它不起作用!

错误:无法将类型'[Int]'的值转换为指定类型'NewStruct'
let newStr:NewStruct = [1,2,3]

我做错了什么或者是否有对ArrayLiteralConvertible进行特殊处理?

解决方案

<一般来说,文字是纯粹编译时的工件。它们可以用来产生一个从该文字初始化的对象,但是一旦编译阶段结束,没有人知道这是一个文字。



这表明任何支持下面的协议需要内置到编译器本身中:


  • ArrayLiteralConvertible

  • BooleanLiteralConvertible

  • DictionaryLiteralConvertible li>
  • ExtendedGraphemeClusterLiteralConvertible

  • FloatLiteralConvertible li>
  • NilLiteralConvertible

  • IntegerLiteralConvertible li>
  • StringLiteralConvertible

  • StringInterpolationConvertible li>
  • UnicodeScalarLiteralConvertible



编译器不会把你自己的协议作为上述任何一项的替代品。

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?

解决方案

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.

这篇关于ArrayLiteralConvertible:只是一个正常的协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆