无法调用类型' Int'的初始化程序。使用类型'(数字)'的参数列表

时间:2017-05-28 07:24:06

标签: swift ipad swift-playground

此程序无法通过Xcode编译,只能在IOS应用程序中运行" Playgrounds"。

在IOS应用程序" Playgrounds" - > "学习编码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)

最后一句显示错误: 无法调用类型' Int'的初始化程序。使用类型'(数字)'的参数列表。 如何将note转换为Int类型?

1 个答案:

答案 0 :(得分:0)

这是在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,可返回该号码的IntDouble表示。

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

因此,如果您需要index成为Int,请执行以下操作:

let index = note.int