【问题标题】:Cannot invoke initializer for type 'Int' with an argument list of type '(Number)'无法使用类型为“(数字)”的参数列表调用类型“Int”的初始化程序
【发布时间】: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


【解决方案1】:

这是在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多