尝试将UITextField文本转换为Int Xcode 7时出现错误

时间:2015-07-19 23:00:40

标签: ios int textfield swift2 xcode7-beta3

我是编程新手,在网上做了一些教程后,我决定使用Xcode 7制作自己的应用程序,以便能够在我的iPhone上运行我的应用程序。但是当我尝试从文本字段获取输入数据并将其放入var时,它会给我一个错误。我试图使用以下内容:

var initialChips = 0
var initialBlind = 0

@IBOutlet weak var txtBlind: UITextField!
@IBOutlet weak var txtChips: UITextField!
@IBOutlet weak var doneBtn: UIBarButtonItem!

@IBAction func doneBtn(sender: AnyObject) {

    let initialChips:Int? = Int(txtChips.text)
    let initialBlind:Int? = Int(txtBlind.text)
}

Xcode会要求输入“!”在“.text”之后,但在这之后它给了我一个警告:“初始化不可变值'initialChips'(或'initialBlind'从未使用过:考虑用赋值替换为'_'或删除它。”

如何为我的var设置值?

2 个答案:

答案 0 :(得分:2)

问题是struct TopicBook { var name: String var species: [String] var subject: String var rotation: [String] var unit: String var extra: String var content: String var level: [(Int,Int)] init(name: String, species: [String], subject: String, rotation: [String], unit: String, extra: String, content: String, level: [(Int,Int)]) { self.name = name self.species = species self.subject = subject self.rotation = rotation self.unit = unit self.extra = extra self.content = content self.level = level } } class ViewController: UIViewController { var extent:TopicBook? var extent2:TopicBook? override func viewDidLoad() { super.viewDidLoad() extent = TopicBook (name: "Name" , species: ["species","species"], subject: "subject", rotation: ["rotation"], unit: "unit", extra: "extra", content: "content", level: [(1,1)]) extent2 = TopicBook (name: "JustToShow" , species: ["JustToShow","JustToShow"], subject: "JustToShow", rotation: ["JustToShow"], unit: "JustToShow", extra: "JustToShow", content: "JustToShow", level: [(2,2)]) } override func viewDidAppear(animated:Bool){ super.viewDidAppear(true) //If you want it to have multiple TopicBooks inside, do this //var seteMutable:[TopicBook] = [ ] //seteMutable =[extent!] //seteMutable.append(extent2!) //let seteTrial = seteMutable //println(seteTrial[0].name) //println(seteTrial[1].name) //else if you want it to have just one TopicBook inside, do this let sete = [extent!] // sete is a TopicBook array now //you can use sete[0] //Placing it inside viewDidAppear is an example, you can define "sete" in anywhere you will use it. //viewDidAppear gets called after viewDidLoad, this is why i put it here } } 生成一个名为let initialChips:Int? = Int(txtChips.text)的新变量(与类中的变量不同)。 initialChipslet之间的区别在于var是不可变的而var不是。你应该这样做:

let

initialChips = Int(txtChips.text) 中的整数分配给类变量,而不是声明一个新的不可变变量(具有相同的名称),并且不执行任何操作。

当然,UITextField

也是如此

修改

尝试以下方法:

initialBlind

答案 1 :(得分:0)

您应该在右括号后添加!,而不是在.text之后添加,如下所示:

let initialChips:Int? = Int(txtChips.text)!