Ios 字符串作为Swift中的对象引用
我的类中有一个名为“game”的对象,我可以访问其中另一个名为“computer1”的对象 例如:Ios 字符串作为Swift中的对象引用,ios,swift,Ios,Swift,我的类中有一个名为“game”的对象,我可以访问其中另一个名为“computer1”的对象 例如: game.computer1.doSomeMethod() 但是,有三台计算机(computer1、computer2、computer3),我随机选择一台计算机,然后使用字符串作为对象引用 我的尝试: var computerNumber = arc4random_uniform(2) + 1 var computer:String = "computer" + String(computer
game.computer1.doSomeMethod()
但是,有三台计算机(computer1、computer2、computer3),我随机选择一台计算机,然后使用字符串作为对象引用
我的尝试:
var computerNumber = arc4random_uniform(2) + 1
var computer:String = "computer" + String(computerNumber)
game.computer.doSomeMethod() // this line doesn't work
我希望避免将随机数传递到对象游戏和一组if-else语句中,然后最终选择使用我选择的对象执行一系列操作
有没有办法解决这个问题?为什么不使用数组而不是属性
class Computer {
let number: Int
init(number: Int) {
self.number = number
}
func doSomeMethod() {
print("doing something with computer \(number)")
}
}
class Game
{
var computers: [Computer]
init() {
computers = [Computer]()
for i in 1...3 {
computers.append(Computer(number: i))
}
}
func callRandomComputer() {
let random = Int(arc4random_uniform(3))
computers[random].doSomeMethod()
}
}
let game = Game()
game.callRandomComputer()
game.callRandomComputer()
game.callRandomComputer()
为什么不使用数组而不是属性
class Computer {
let number: Int
init(number: Int) {
self.number = number
}
func doSomeMethod() {
print("doing something with computer \(number)")
}
}
class Game
{
var computers: [Computer]
init() {
computers = [Computer]()
for i in 1...3 {
computers.append(Computer(number: i))
}
}
func callRandomComputer() {
let random = Int(arc4random_uniform(3))
computers[random].doSomeMethod()
}
}
let game = Game()
game.callRandomComputer()
game.callRandomComputer()
game.callRandomComputer()
使用数组而不是三个单独的属性使用数组而不是三个单独的属性感谢您的帮助!谢谢你的帮助!