xcode 字符串不可转换为 int (Swift)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25334908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
string is not convertible to int (Swift)
提问by quemeful
This is the code I have (my actual code is more complex, but I simplified it down, and I still get this error):
这是我的代码(我的实际代码更复杂,但我简化了它,但仍然出现此错误):
let x = "1" as Int
Xcode says:
Xcode 说:
'String' is not convertible to 'Int'
Am I missing something or is this a beta bug?
我错过了什么还是这是一个测试版错误?
回答by Mundi
You cannot simply cast with as
. There is a method that produces Int
explicitly.
你不能简单地用as
. 有一种方法可以Int
显式生成。
let x = "1".toInt()
Notice that the result is of type Int?
because Swift cannot know upfront if the conversion succeeds.
请注意,结果是类型的,Int?
因为 Swift 无法预先知道转换是否成功。
println(x!)
Or:
或者:
let x = "1".toInt()!
回答by CAN
I hope this helps you thats how it should be
我希望这对你有帮助 那应该是这样
let x = "1".toInt()