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

时间:2022-03-18 11:14:21

This program can't compile by Xcode, it only run in IOS application "Playgrounds".

这个程序不能通过Xcode编译,它只能在IOS应用程序“Playgrounds”中运行。

In IOS application "Playgrounds" -> "Learn to Code 3"(Swift 3.1) ->"Music Universe" I have below code:

在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

The above just for explanation.

以上只是为了解释。

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

The last sentence show error: Cannot invoke initializer for type 'Int' with an argument list of type '(Number)'. How can I convert note to Int type?

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

1 个解决方案

#1


1  

This is running on the iPad application Swift Playgrounds.

这是在iPad应用程序Swift Playgrounds上运行的。

They apparently have created a protocol Number behind the scenes to ease the pain of Swift type conversions. In this mini program, it is possible to multiply an Int and a Double without first converting the Int to a Double:

他们显然在幕后创建了一个协议编号,以减轻Swift类型转换的痛苦。在这个迷你程序中,可以将Int和Double相乘,而无需先将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 has read-only properties int and double which return the Int and Double representations of the number.

Number具有只读属性int和double,它返回数字的Int和Double表示。

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

So, if you need index to be an Int, do it like this:

所以,如果你需要索引成为一个Int,那就这样做:

let index = note.int

#1


1  

This is running on the iPad application Swift Playgrounds.

这是在iPad应用程序Swift Playgrounds上运行的。

They apparently have created a protocol Number behind the scenes to ease the pain of Swift type conversions. In this mini program, it is possible to multiply an Int and a Double without first converting the Int to a Double:

他们显然在幕后创建了一个协议编号,以减轻Swift类型转换的痛苦。在这个迷你程序中,可以将Int和Double相乘,而无需先将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 has read-only properties int and double which return the Int and Double representations of the number.

Number具有只读属性int和double,它返回数字的Int和Double表示。

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

So, if you need index to be an Int, do it like this:

所以,如果你需要索引成为一个Int,那就这样做:

let index = note.int