gpt4 book ai didi

arrays - [Int] 和 Array 有什么区别?

转载 作者:可可西里 更新时间:2023-11-01 00:15:18 25 4
gpt4 key购买 nike

let numberList = Array(1...10) // type == Array<Int>
let numberList2 = [1,2,3,4,5,6,7,8,9,10] // type == [Int]

上面的代码将注释类型分配给每个常量。我不记得在文档中遇到过对此的解释。

这只是一种情况,一种使用构造函数,另一种使用文字表示法,结果产生了不同的类型?

如果是这样,一旦它们被声明,使用一个与另一个有什么区别吗? (即使用构造函数允许您使用类初始化器等。但是在初始化后,一个比另一个提供任何好处吗?)

一旦初始化,它们似乎都使用相同的数组 API。所以我假设这完全是语法上的?

最后,有什么方法可以通过字面量来模拟构造函数的功能吗?例如

let arr = [](1...10) // doesn't create [1,2,3,4,5,6,7,8,9,10]

有点不相关

谁能告诉我为什么下面的代码会产生这样的结果?:

let numberList2 = [1...10] // == ["1..<11"]

我认为上面是一个包含范围的数组。 Playground 中显示的类型报告类型为:[Range],如预期的那样。但是,为什么该值看似报告为一个数组,其中包含一个表示最大 11 的半开范围的字符串,而不是最大 10 的闭范围?

对于脱节的帖子深表歉意。在此先感谢您的帮助。

最佳答案

来自 The Swift Programming Language: Collection Types

Array Type Shorthand Syntax

The type of a Swift array is written in full as Array<SomeType>, where SomeType is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [SomeType]. Although the two forms are functionally identical, - the shorthand form is preferred and is used throughout this guide when referring to the type of an array.

也就是说,两个注释都是正确的 - 都代表相同类型。

关于arrays - [Int] 和 Array<Int> 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com