import Foundation
import UIKit
class GameController: UIViewController {
@IBOutlet weak var gameImage: UIImageView!
@IBOutlet weak var softButton: UIButton!
@IBOutlet weak var notButton: UIButton!
@IBOutlet weak var scoreLabel: UILabel!
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
self.gameImage.image = UIImage(named: "king1")
}
//choose random image and set as game image
func randomGameImage() -> String {
//these arrays hold the image names
let kingArray = ["king1", "king2", "king3"]
let notArray = ["not1", "not2", "not3"]
//this number decides which array to pull from
let randomNumber = Int(arc4random_uniform(2))
//this number picks what image from the array
let imageNumber = Int(arc4random_uniform(3))
//holds the name of the image
var gameImageString:String
//sets image name
if randomNumber >= 1 {
gameImageString = kingArray[imageNumber]
}else{
gameImageString = notArray[imageNumber]
}
//sets image
self.gameImage.image = UIImage(named: gameImageString)
//returns name of image
return gameImageString
}
var bool = true
var score = 0;
var imageShowing:String = randomGameImage()//"king"
(使用实例方法' randomGameImage'在类型' GameController';您的意思是使用类型' GameController'的值?)
@IBAction func kingTapped(sender: AnyObject) {
if imageShowing.rangeOfString("king") != nil {
score += 1
scoreLabel.text = String(score)
imageShowing = randomGameImage()
}else{
performSegueWithIdentifier("gameOver", sender: bool)
}
}
@IBAction func notTapped(sender: AnyObject) {
if imageShowing.rangeOfString("not") != nil {
score += 1
scoreLabel.text = String(score)
imageShowing = randomGameImage()
}else{
performSegueWithIdentifier("gameOver", sender: bool)
}
}
}
有人可以告诉我为什么我可以在其他方法中调用randomGameImage方法,但不能在方法之外调用。对不起,我是编程菜鸟。
答案 0 :(得分:0)
原因与此相同: Swift Computed properties cannot be used in init?
在Swift的两阶段初始化中,在完成阶段1之前,您无法访问self
。在调用init
之前,在阶段1的第一阶段为属性分配默认值。因此,您不能在存储属性的默认值表达式中使用self
,这意味着您无法调用实例方法,也无法使用其他实例属性。
您可以使用类方法或全局函数作为初始值。