【问题标题】:Can't call function from other class不能调用其他类的函数
【发布时间】:2016-01-25 11:44:12
【问题描述】:

所以我试图从我的分数类中调用一个函数,该函数会将分数加一:

Score.addOneToScore(1)

但我最终得到了这个错误:

无法将“Int”类型的值转换为预期的参数类型“Score”

我很确定我忽略了一些东西,但我似乎看不到它。

这是我的分数等级:

import Foundation
import SpriteKit
import UIKit


class Score: SKLabelNode {

var number = 0

init (num: Int) {

    super.init()

    fontColor = UIColor.whiteColor()
    fontName = "Helvetica"
    fontSize = 75.0


    number = num
    text = "\(num)"

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func addOneToScore() {

    number++
    text = "\(number)"

  }

}

【问题讨论】:

  • func addOneToScore() 在定义中不接受任何参数。但你通过了它 1?
  • 如果我取出一个并在没有它的情况下调用它,那么它只会给我另一个错误,说它在调用中缺少参数 #1 的参数,我也无法真正弄清楚为什么。
  • @Astrum 因为你不应该使用它(就像它是一个静态函数一样)。 addOneToScore() 是一个实例方法。看看 Greg 的回答,看看你应该如何使用你的代码。

标签: swift function class sprite-kit uilabel


【解决方案1】:

您犯的错误很少: 你正试图打电话 addOneToScore() 作为类(静态)函数,但它是实例函数,并且您正在传递参数但函数不接受,试试这个:

let score = Score(num: 0) // Initialise score with the value of 1
score.addOneToScore() // add one to the score
print("\(score.number)") // print the value (1)

【讨论】:

  • 是的,它修复了它,但由于某种原因它没有添加到分数中
  • 你应该在你需要的类级别中添加一个常量: let score = Score(num: 0) (在类'你的类名'之后添加这一行)并调用 score.addOneToScore () 你需要它的地方。
  • 你的答案有效,但它似乎并没有改变分数标签来显示数字 1,它只是一直显示 0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多