当我遇到这个问题时,我正在研究Swift上的这个教程。
码
var languagesLearned: String = "3"
if let num: Int? = Int(languagesLearned)
{
print("It is a number")
}
else
{
print("It is not a number")
}
错误:
Playground execution failed: /var/folders/f7/0j8dbxls0kv0l9d6jwk30f2h0000gn/T/lldb/20598/playground134.swift:72:20: error: cannot invoke 'init' with an argument of type '@lvalue String'
if let num: Int? = Int(languagesLearned)
^~~~~~~~~~~~~~~~~~~~~
我找不到任何关于我为何会遇到此类错误的信息。我也不知道它对init的评价。
答案后更正的代码
var languagesLearned: String = "3"
var languagesLearnedNum = languagesLearned.toInt()
if let num = languagesLearnedNum
{
print("It is a number")
}
else
{
print("It is not a number")
}
答案 0 :(得分:1)
在Swift 1.x中,使用:
languagesLearned.toInt()