我在用swift向类传递值时遇到问题,我有ViewControler.swift来创建对象和其他UI类型的东西。代码如下:
class ViewController: UIViewController {
//creates the Intractive button objects
@IBOutlet var Bag1: UIButton!
@IBOutlet var Bag2: UIButton!
@IBOutlet var Bag3: UIButton!
@IBOutlet var lblTokenSlider: UILabel!
@IBOutlet var slider: UIStepper!
@IBOutlet var Go: UIButton!
@IBOutlet var counter: UILabel!
var count = 10
var noOfBags = 3
//gives acces to game AP!
var gameAPI = GameAPI(noOfBags: count, noOfTokens: noOfBags )
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
lblTokenSlider.hidden = true
slider.hidden = true
Go.hidden = true
counter.hidden = true
Bag3.hidden = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Event Drivers
@IBAction func btnBag1(sender: AnyObject) {
Bag1.userInteractionEnabled = false
Bag2.userInteractionEnabled = false
Bag3.userInteractionEnabled = false
}
@IBAction func btnBag2(sender: AnyObject) {
}
@IBAction func btnBag3(sender: AnyObject) {
}
@IBAction func SliderAction(sender: AnyObject) {
}
@IBAction func RemoveTokens(sender: AnyObject) {
}
}
}
这是我的gameAPI:
import Foundation
private enum MoveError: ErrorType {
case Empty
}
class GameAPI {
var noOfBags: Int
var bagArray:[Bag] = []
init(noOfBags: Int, noOfTokens : Int){
self.noOfBags = noOfBags
for _ in 0..<noOfBags {
bagArray.append(Bag(counter: noOfTokens))
}
}
/* Returns the amount of counters are in a bag */
func getCounts(i :Int ) -> Int {
return bagArray[i].getCount()
}
func isBagEmpty(i: Int) -> Bool {
if (bagArray[i].getCount() <= 0){
return true
}
else {
return false
}
}
func removeCounter(bagToRemove: Int, counters: Int ) throws{
do {
try self.bagArray[bagToRemove].removeCount(counters)
}
catch{
throw MoveError.Empty
}
}
}
问题是我在ViewController中声明GameAPI时
不能对类型“ViewController”使用“Instance member”count
在线
var gameAPI = GameAPI(noOfBags: count, noOfTokens: noOfBags )
但如果我把变量换掉,使用固定值,比如:
var gameAPI = GameAPI(noOfBags: 10, noOfTokens: 3 )
它工作得很好。我真的不明白为什么这不管用。
谢谢你
最佳答案
问题是,您有一个实例变量的初始值设定项使用另一个实例变量。通常,在初始化所有实例变量之前,不能使用实例变量。因此,必须打破实例变量之间的依赖关系。
你有几个选择:
将初始化移到初始化程序。不过,这对于UIViewController
来说有点困难,因为您至少需要两个初始值设定项,这会导致代码重复:
init(...) {
let count = 10
let noOfBags = 3
self.count = count
self.noOfBags = noOfBags
self.gameAPI = GameAPI(noOfBags: count, noOfTokens: noOfBags)
super.init(...)
}
声明
count
和noOfBags
为全局常量:static let count = 10
static let noOfBags = 3
因此,
GameAPI
初始值设定项不会使用self
。如果需要
count
和noOfBags
作为变量,可以创建全局常量initialCount
和initialNoOfBags
,然后var count = initialCount
var noOfBags = initialNoOfBags
var gameAPI = GameAPI(noOfBags: initialCount, noOfTokens: initialNoOfBags)
您可以懒洋洋地初始化您的
gameAPI
:lazy var gameAPI: GameAPI = GameAPI(noOfBags: self.count, noOfTokens: self.noOfBags)
关于ios - 'count'不能用于'ViewController'类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38816847/