【发布时间】:2017-01-06 00:30:51
【问题描述】:
我想学习如何在初始化期间使用使用字符串的霹雳舞枚举来设置独特的天才舞蹈属性。我认为它会起作用,但是当我尝试在 init 中设置属性的不同变体时,我会遇到编译错误,例如“将属性分配给自身”和许多其他错误。我的想法已经用完了,但我知道这是可能的,因为一些 Cocoa 类在初始化期间执行此操作,例如 UITableView 在选择首选样式时。
import Foundation
enum Breakdances: String {
case HoppityHop = "Hop Hop Hop and two step is what I do usually"
case Greyjoy = "I made up this dance, pretty cool huh?"
case ButtSwirl = "Let's do the butt swril"
case PsychMovementWithHands = "Psych, Psych, Psych! Psych"
case TheDab = "Dabbbbb!"
case TheBump = "I'm doing the rump bump dance"
}
class Monkeys: Animals, canPlayAroundProtocol, randomJungleActivity {
static var monkeysPopulation: Int = 0
var uniqueGiftedDance: Breakdances
override init(name:String){
super.init(name: name)
self.uniqueGiftedDance = uniqueGiftedDance
Monkeys.monkeysPopulation += 1
}
override func makeSound() -> String {
energyLevel -= 4
return "Ah ah ah"
}
override func eatFood(){
energyLevel += 2
}
override func sleep(){
}
func play(){
let reducedEnergy = energyLevel - 8
if reducedEnergy < 0 {
print("\(name) is too tired, I don't have enough energy")
}else {
print("Oooo Oooo Oooo")
print("\(name)'s energy level is now \(reducedEnergy)")
}
}
func startUniqueJungleAct(){
print(uniqueGiftedDance)
print("Swinging from a tree and throwing banannas")
}
deinit {
Monkeys.monkeysPopulation -= 1
}
}
这是我的父类:
import Foundation
protocol canPlayAroundProtocol {
func play()
}
protocol randomJungleActivity {
func startUniqueJungleAct()
}
class Animals {
static var animalPopulation: Int = 0
var name: String!
var energyLevel: Int = 100
init(name: String) {
self.name = name
Animals.animalPopulation += 1
print("Another animal has given birth, animal population is now \(Animals.animalPopulation)")
}
func makeSound() -> String{
energyLevel -= 3
return "null"
}
func eatFood() {
energyLevel += 5
}
func sleep(){
energyLevel += 10
}
static func junglePerformSoundOff(){
}
func bathroomSound(){
}
deinit {
Animals.animalPopulation -= 1
}
}
【问题讨论】:
-
您希望
uniqueGiftedDance来自哪里? -
您发布的代码有很多不相关的材料。人们不想通过所有这些来达到目的。请发帖minimal, complete, and verifiable example。
-
@Alexander 谢谢,我想在创建新的 Monkey 实例时设置它。所以每只猴子都有自己独特的GiftedDance。希望我回答了你的问题。
-
所以你会想在初始化过程中将它作为一个参数,对吗?
-
那么...将其作为参数添加到初始化程序