我是Swift的新手,并尝试制作一些可以替代其他随机单词的单词。 (如果你有任何进一步的建议,让它更好地工作,拜托!我很满意。)
我尝试在ViewController之后调用UITextView对象中的文本,一切都很好。当我构建并按下我的按钮时,我得到以下错误:
致命错误:在解包可选值时意外发现nil
我在这里做错了什么?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
maintext.text = "The Dog Chases the Ball"
self.submit.setTitle("Change It", forState: UIControlState.Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet var maintext: UITextView!
@IBOutlet var submit: UIButton!
@IBAction func submitTapped(sender: UIButton) {
self.submit.setTitle("Again", forState: UIControlState.Normal)
wordSwapper()
}
}
var maintext: UITextView!
var AllWords : String! = maintext.text!
// Word Replacer Engine
extension Array {
func randomItem() -> T {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
extension String {
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}
// Text imported from Text Box
//: Old Text Loaded as an array
class wordSwapper {
var Dog = ["Pup", "Canine", "Wolf"]
var Ball = ["Frisbee", "Stick", "Car"]
init(){
var WordsArray = AllWords.componentsSeparatedByString(" ")
//: New Word Library
AllWords.replace("Dog", withString: Dog.randomItem()).replace("Ball", withString: Ball.randomItem())
for Dog in WordsArray {
AllWords.replace("Dog", withString: "Pup")
}
for Ball in WordsArray {
AllWords.replace("Ball", withString: "Frisbee")
}
}
}
答案 0 :(得分:0)
您在此处覆盖您的IBOutlet:
var maintext: UITextView!
这就是你的方法wordSwapper()中为零的原因。
答案 1 :(得分:0)
我仍然掌握着swift,并意识到我正在从两个不同的类中调用一个变量。 maintext类是视图控制器的变量,所以我不得不在我首先创建的新类中调用视图控制器。