Swift为.toInt提供Optional(3)而不是3 [英] Swift giving Optional(3) instead of 3 for .toInt

查看:62
本文介绍了Swift为.toInt提供Optional(3)而不是3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从字段中提取数字并继续获取可选(数字)而不是数字

Trying to pull a number from a Field and keep getting Optional(number) instead of the number

@IBOutlet weak var years: UITextField!

@IBAction func calculateYear(sender: AnyObject) {

    var a = years.text.toInt()
    println(a)
}

如果3在该字段中获得可选(3)

if 3 is in the field getting Optional(3)

如果我使用 years.text 我得到了正确的输出,但它是一个字符串,我可以工作用它来。

if I use years.text I get the right output but it is a string and I can's work with it.

使用Xcode 6.1

using Xcode 6.1

推荐答案

这是因为 toInt()方法返回一个可选项,以说明当字符串无法转换为整数时的情况。

That happens because the toInt() method returns an optional, to account for the case when the string is not convertible to an integer.

只需将其放入可选绑定中:

Just put that in an optional binding:

if let a = a {
    println(a)
}

这篇关于Swift为.toInt提供Optional(3)而不是3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆