【发布时间】:2017-05-28 07:24:05
【问题描述】:
此程序无法通过 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)
最后一句显示错误:
无法使用类型为“(数字)”的参数列表调用类型“Int”的初始化程序。
如何将note 转换为Int 类型?
【问题讨论】:
-
touch.position.x是什么类型? – 一个独立的示例来说明问题会很有帮助。 -
乍一看,我认为
touch.position.x类型是CGFloat,但似乎不是因为你应该在let note = normalizedXPosition * (numberOfNotes - 1)上得到一个编译时错误,抱怨Int和CGFloat之间的乘法. -
我添加了touch.position.x的注释,touch.position.x类型是
Double -
您更新的代码无法编译(“struct Touch”后缺少大括号,未定义类型“Point”)。但如果 touch.position.x 是 Double 则
let note = ...行已经无法编译。 -
好吧,那我假设你应该在
let note = normalizedXPosition * (numberOfNotes - 1)这一行得到一个错误,抱怨:cannot apply*between Double and Int...
标签: swift ipad swift-playground