var arr: [Double] = Array(stride(from: 0, through: 11, by: 1.0))
这段代码没问题,但是如果我写这个,就会出现“无法调用”的问题
var s = 11
var arr: [Double] = Array(stride(from: 0, through: s, by: 1.0))
为了让您的stride
语句产生,Double
传递给 的值from
必须是s。through
by
Double
在第一种情况下,Swift 推断字面量0
和11
是Double
s,因为1.0
是 a Double
,这是它们匹配的唯一方法。这是有效的,因为Double
符合ExpressibleByIntegerLiteral
协议,这意味着您可以Double
使用整数文字初始化 a ,并且可以在Double
必要时推断整数文字为 a 。
在第二种情况下,您已经分配11
给s
并且 Swift 分配s
了 type Int
。因此,当您尝试在stride
语句中使用它时,类型不匹配。
您可以通过多种方式解决此问题:
s
成为一个Double
with var s: Double = 11
。在这种情况下,您已经明确指定了 的类型s
,因此 Swift 使用ExpressibleByIntegerLiteral
符合 的Double
来初始化s
。11
是一个Double
with var s = 11 as Double
。在这里,您已经告诉 Swift 这11
是Double
因为Double
符合ExpressibleByIntegerLiteral
. 斯威夫特然后推断类型s
也为Double
。11
为。这使用了一个将 a作为输入的初始化程序。然后 Swift从分配给它的值推断出的类型。Double
var s = Double(11)
Double
Int
s
Double
s
与 .一起使用时转换Double(s)
。在这里,您显式使用Double
初始化程序来创建Double
带有Int
s
.s
用Double
文字声明with var s = 11.0
。在这里,Swift 推断字面11.0
量是类型Double
,然后推断类型s
也是 a Double
,因为它是由 a 初始化的Double
。