Swift错误:二进制运算符==不能用于输入'_'和'Int'

问题描述:

我是Swift的全新用户,我正在尝试构建一个简单的程序,以告诉用户哪一年中国人的日历是根据他们的年龄出生的。Swift错误:二进制运算符==不能用于输入'_'和'Int'

var string1 = "You are year of the" 
    let age:Int? = Int(ageField.text!) 

    if age <= 12 { 
     let remainder = age! 
    } else { 
     let remainder = age! % 12 
    } 

    if remainder == 0 { 
     string1 += " sheep." 
    }; if remainder == 1 { 
     string1 += " horse." 
    }; if remainder == 2 { 
     string1 += " snake." 
    }; if remainder == 3 { // And so on and so forth... 

我得到说,二进制运算符“==”不能应用于类型“_”和“诚信”的操作数上的每个“如果”行一个错误消息。任何想法我可以做什么来解决这个问题?

+0

假设“age

+1

你需要测试'age'是否为'nil'。 'let age:Int = Int(ageField.text!)''ageField.text' ==“Grimxn”会导致你以后的任务崩溃(一旦他们编译) - 请参阅下面的@ AlessandroChiarotto的答案。 – Grimxn

变量/常量remainder应该在if构造之外声明,也可以删除字符“;”在你的代码中。斯威夫特不需要“;”在像Objective-C的

+0

Got it!谢谢! –

由于亚历山德罗的答案的总结和评论的指令后,你的优化代码可能看起来像

var string1 = "You are year of the" 
if let age = Int(ageField.text!) { 

    let remainder = age % 12 

    if remainder == 0 { 
     string1 += " sheep." 
    } else if remainder == 1 { 
     string1 += " horse." 
    } else if remainder == 2 { 
     string1 += " snake." 
    } // And so on and so forth... 

} else { 
    print("please enter a number") 
} 

或有点“swiftier”使用switch声明

var string1 = "You are year of the " 
if let age = Int(ageField.text!) { 

    switch age % 12 { 

    case 0: string1 += "sheep." 
    case 1: string1 += "horse." 
    case 2: string1 += "snake." 
     // And so on and so forth... 
    } 

} else { 
    print("please enter a number") 
} 

PS:其实这只羊是一只山羊;-)