简体   繁体   English

Swift - 使用命名变量声明一个集合

[英]Swift - Declaring a Set using named variable

I am trying to understand Sets in Swift and how to declare them correctly but I have found the following a little confusing.我试图了解 Swift 中的集合以及如何正确声明它们,但我发现以下内容有点令人困惑。

I understand that this works:我知道这有效:

let elements = [ 1, 2, 3, 4, 5, 1, 2, 6, 7]
let setFromElements = Set(elements)

But I don't understand why the following doesn't:但我不明白为什么以下内容不:

let setFromElements : Set = elements

Or even:甚至:

let setFromElements : Set<Int> = elements

When the following is valid:当以下情况有效时:

let setFromArray : Set = [ 1, 2, 4, 5]

Can someone please help me understand why this is the case?有人可以帮我理解为什么会这样吗?

let setFromArray: Set = [ 1, 2, 4, 5] works because Set conforms to ExpressibleByArrayLiteral and hence has an initializer that takes an ArrayLiteral . let setFromArray: Set = [ 1, 2, 4, 5]之所以有效,是因为Set符合ExpressibleByArrayLiteral ,因此有一个采用ArrayLiteral的初始化程序。 See Set.init(arrayLiteral:) .请参阅Set.init(arrayLiteral:) This conformance gives syntactic sugar for not having to explicitly call the init.这种一致性为不必显式调用 init 提供了语法糖。

On the other hand, once you save the array literal into a variable using let elements = [ 1, 2, 3, 4, 5, 1, 2, 6, 7] , elements becomes an Array , not an ArrayLiteral and hence another initializer of Set has to be called that takes an Array .另一方面,一旦使用let elements = [ 1, 2, 3, 4, 5, 1, 2, 6, 7]将数组文字保存到变量中, elements就会变成Array ,而不是ArrayLiteral ,因此是另一个初始化程序of Set必须被调用,它需要一个Array This init does not provide syntactic sugar like ExpressibleByArrayLiteral does, so you explicitly have to call the init by doing Set(array) .此 init 不像ExpressibleByArrayLiteral那样提供语法糖,因此您必须通过Set(array)显式调用 init。

Set has an initializer that takes an array , and that makes a set, by taking the unique items in the array. Set 有一个初始化器,它接受一个数组,并通过获取数组中的唯一项来创建一个集合。 But a set is not an array , two different types, so you can't just use = to assign one to the other.但是set不是array ,两种不同的类型,所以你不能只使用=将一个分配给另一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM