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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:23:45  来源:igfitidea点击:

string is not convertible to int (Swift)

xcodestringswiftint

提问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 Intexplicitly.

你不能简单地用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()