2015-12-14 61 views
1

我是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 <= 12」實際上應該是「age <12」(爲了得到0到11之間的餘數),沒有必要TES這一點。只要'讓餘數=年齡! %12'。 –

+1

你需要測試'age'是否爲'nil'。 'let age:Int = Int(ageField.text!)''ageField.text' ==「Grimxn」會導致你以後的任務崩潰(一旦他們編譯) - 請參閱下面的@ AlessandroChiarotto的答案。 – Grimxn

回答

2

變量/常量remainder應該在if構造之外聲明,也可以刪除字符「;」在你的代碼中。斯威夫特不需要「;」在像Objective-C的

+0

Got it!謝謝! –

2

由於亞歷山德羅的答案的總結和評論的指令後,你的優化代碼可能看起來像

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:其實這隻羊是一隻山羊;-)

相關問題