我正在尝试编写一个具有以下规则的正式系统:
有四种推理规则: 1)如果字符串的最后一个字符是" I",你可以添加" U"到字符串(例如:MI - > MIU)
2)x是一系列字母,Mx可以用Mxx代替(例如:MIU - > MIUIU)
3)如果字符串包含" III",您可以替换" III"与" U" (例如:MUIII - > MUU)
4)如果字符串包含" UU",您可以删除" UU"部分(例如:MIIUU - > MII)
在我的项目中,规则1对应于button1,规则2对应于button2,规则3对应于button3,规则4对应于按钮4
此外,由于用户有时可能会陷入无限循环(例如:如果你进入" MIU",从那时起,你只能使用规则2并获得" MIUIU&#34 ;等等)我添加了一个" clear"按钮。 我希望清除按钮只需将Label.text转换为" MI"所以用户可以回到起点并重试
关键在于,出于某种原因,当我按下"清除"按钮Label.text没有变成" MI"正如我想要的那样,但它变成了" MIU"代替!
我错过了什么?
PS:我知道这可能非常容易让我感到困惑,但我没有太多的编程经验这是我的代码: 导入UIKit
class ViewController: UIViewController {
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var rule1Button: UIButton!
@IBOutlet weak var rule2Button: UIButton!
@IBOutlet weak var rule3Button: UIButton!
@IBOutlet weak var rule4Button: UIButton!
@IBOutlet weak var clearButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
clear()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var string : String = "MI"
var string1 : String = ""
func rule1() {
if string.characters.last == "I" {
string.append("U")
Label.text = string
}
}
func rule2() {
string1 = string.replacingOccurrences(of: "M", with: "")
string = string + string1
Label.text = string
}
func rule3() {
string = self.string.replacingOccurrences(of: "III", with: "U")
Label.text = string
}
func rule4() {
string = self.string.replacingOccurrences(of: "UU", with: "")
Label.text = string
}
func clear() {
string = "MI"
Label.text = string
}
@IBAction func rule1Button(_ sender: Any) {
rule1()
}
@IBAction func rul2Button(_ sender: Any) {
rule2()
}
@IBAction func rule3Button(_ sender: Any) {
rule3()
}
@IBAction func rule4Button(_ sender: Any) {
rule4()
}
@IBAction func clearButton(_ sender: Any) {
clear()
}
}
答案 0 :(得分:0)
代码很好 - 你在@IBActions和Buttons之间的故事板中肯定有错误的连接。
重新连接所有这些,你应该没事。
如果右键单击故事板中的UIButton,则会提供与其连接的IBAction的信息。
检查所有按钮并修复损坏的按钮。
除此之外,您的代码可以简化很多,我建议您使用didSet
将变量值保存为UILabel
文本。
var string : String = "" { //no need for default value here, as you are calling clear() on viewDidLoad(), better keep constants in one place
didSet {
Label.text = string
}
}
func rule1() {
if string.characters.last == "I" {
string = string + "U"
}
}
func rule2() {
string = string + string.replacingOccurrences(of: "M", with: "")
}
func rule3() {
string = self.string.replacingOccurrences(of: "III", with: "U")
}
func rule4() {
string = self.string.replacingOccurrences(of: "UU", with: "")
}
func clear() {
string = "MI"
}