无法使用“(Number)”类型的参数列表调用类型 'Int' 的初始值设定项

Cannot invoke initializer for type 'Int' with an argument list of type '(Number)'

这个程序不能被Xcode编译,它只能运行在IOS应用"Playgrounds".

在 IOS 应用程序 "Playgrounds" -> "Learn to Code 3"(Swift 3.1) ->"Music Universe" 我有以下代码:

// A touch event for when your finger is moving across the scene.

// Declaration
struct Touch

// The position of this touch on the scene.

// Declaration
var position: Point

// The x coordinate for the point.

// Declaration for touch.position.x
var x: Double

以上仅作说明。

let touch: Touch
let numberOfNotes = 16
let normalizedXPosition = (touch.position.x + 500) / 1000
let note = normalizedXPosition * (numberOfNotes - 1)
let index = Int(note)

最后一句显示错误: 无法使用“(Number)”类型的参数列表调用类型 'Int' 的初始值设定项。 如何将 note 类型转换为 Int 类型?

这是 iPad 应用 Swift Playgrounds.

上的 运行

他们显然在幕后创建了一个 protocol Number 来减轻 Swift 类型转换的痛苦。在这个小程序中,可以将 IntDouble 相乘,而无需先将 Int 转换为 Double:

let a = 5      // a is an Int
let b = 6.3    // b is a Double
let c = a * b  // This results in c being type Number

Number 具有只读属性 intdouble,其中 return 数字的 IntDouble 表示。

var int: Int { get }
var double: Double { get }

因此,如果您需要 index 成为 Int,请这样做:

let index = note.int