为你们所有人提供了一个相当基本的Swift问题。
我的目标:能够在arc4random中使用变量(数组中的项目数)。
问题:我不知道如何移动" balloonCount"在createBalloons()函数之外。
解决方案?定义" balloonCount"在currentIndex之上,程序将识别此变量。 (我被告知这是解决方案,我很遗憾不知道如何做到这一点......)
这是我的(更新的)快速代码:
//
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var balloonsLabel: UILabel!
@IBOutlet weak var backgroundImageView: UIImageView!
var balloons:[Balloon] = []
var currentIndex = Int(arc4random_uniform(UInt32(balloons.count)))
' ViewController.type'没有名为' balloons'
的成员override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.createBalloons()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func nextBalloonBarButtonItemPressed(sender: UIBarButtonItem) {
let balloon = balloons[currentIndex]
'的ViewController'没有名为' currentIndex'
的成员 balloonsLabel.text = "\(balloon.number) Balloon"
backgroundImageView.image = balloon.image
currentIndex = currentIndex + 1
'的ViewController'没有名为' currentIndex'
的成员 if currentIndex > 99 {
'的ViewController'没有名为' currentIndex'的成员 currentIndex = 50 }
}
func createBalloons () {
for var balloonCount = 0; balloonCount <= 99; ++balloonCount{
var balloon = Balloon()
//I dont think you need a switch here.
let randomNumber = Int(arc4random_uniform(UInt32(4)))
let balloonName:String = "redBalloon\(randomNumber).jpg"
balloon.image = UIImage(named: balloonName)
balloon.number = balloonCount
self.balloons.append(balloon)
}
}
}
答案 0 :(得分:2)
试试这个,不确定语法是否100%。我在这个comp上没有Xcode。如果这有点帮助我,请告诉我。此外,如果有人看到任何看似错误的地方,请在下面发表评论,我会更新我的答案。
试试这个:
var currentIndex = Int(arc4random_uniform(UInt32(balloons.count)))
我也在这里做了一些改变:
func createBalloons () {
for var balloonCount = 0; balloonCount <= 99; ++balloonCount{
var balloon = Balloon()
//I dont think you need a switch here.
let randomNumber = Int(arc4random_uniform(UInt32(4)))
let balloonName:String = "redBalloon\(randomNumber).jpg"
balloon.image = UIImage(named: balloonName)
balloon.number = balloonCount
self.balloons.append(balloon)
}
}
答案 1 :(得分:1)
我认为您不能将函数分配给使用其他实例变量的变量。
我将currentIndex设为Int,然后创建一个单独的getRandomIndex函数。所以代码看起来像这样:
var currentIndex: Int!
func getRandomIndex() -> Int {
return Int(arc4random_uniform(UInt32(balloons.count)))
}
@IBAction func nextBalloonBarButtonItemPressed(sender: UIBarButtonItem) {
currentIndex = getRandomIndex()
let balloon = balloons[currentIndex]
...