# Swift運算式

%餘數

`var number = 10number += 20number = number + 20`

`let number1 = 10let number2 = 30.5let number3 = Double(number1) + number2`

string interpolation (字串置換) \()

`var age = 18var name = “buffyyao”var message = “我的名字是\(name)，今年\(age)歲”`

`<`
` <= `
`>`
` >=`
` == 剛好相等`
` !=`

if{} /else{} / else if{}

nested if

`if{`
`}`
`else{`
`if{`
`}`
`else{`
`}`
`}`

n線

`if age < 30 {...}`
`else if age <50 {...}`
`else{...}`

&& 全部滿足,缺一不可

|| 知足,只要一個滿足就好

! 相反

`var age = 35var weight = 45if !(age < 30) {}`

..< 含頭去尾 ex: 1..< 3 : 1,2

…頭尾包含 ex: 1…3 : 1,2,3

for…in..

`var sum = 0for i  in 1…1000{ sum = sum + i}`

i = 1,sum = 0 →sum = sum + 1

i = 2, sum = 1 → sum = sum + 2

i = 1000 →sum = sum + 1000

while

repeat while: 至少一次

`repeat{`
`number = number - 1`
`}while number > 0`

cmd + /

optional

`var age: Int?`
`var age:Int? = nil`

`var age:Int? = 18`
`age = age! +1`

force-unwrap on nil →runtime error

`var age:Int? = 18`
`if let ageNumber = age{`
`age = ageNumber + 1`
`}`

!: 自動取值的 Implicitly Unwrapped Optionals

(風險在nil自動取值 -> Crash）

`var age:Int! = 18`
`age = age +1`

function: 函數

function 裡定義一連串程式碼,甚至可能有幾百行,

print(“Peter Pan”): 呼叫函數,執行函數

`//定義func addToNumberfunc addToNumber() {  print(“開始計算”)  var sum = 0  for i in 1...100 {    sum = sum + i   }  print(“結束計算”) }`
`print(“計算前”) addToNumber()  //呼叫funcprint(“計算後”)`

result

`計算前開始計算結束計算計算後`

`func addToNumber(number:Int){  var sum = 0  for i in 1...number {     sum = sum + i  } }`
`addToNumber(number:100)`

*swift在呼叫func時帶名稱

_取消自動產生的外部參數名

`func eat(name:String,  _ price:Int) {`
`}eat(name: "milk", 300)`

`func addToNumber(startNumber:Int, endNumber:Int) -> Int {  var sum = 0  for i in startNumber...endNumber {  sum = sum + i   }  return sum }`
`var sum1 = addToNumber(startNumber:1, endNumber: 100)var sum2 = addToNumber(startNumber:200, endNumber: 300)var sum3 = sum1 + sum2`

`func calculate(start:Int, end:Int, multiple:Int) -> Int { var sum = 0 for i in start…end { if i % multiple == 0 { sum = sum + i } } return sum}calculate(start: 1, end: 12, multiple: 5)`

print（）

terminator:”” 不換行 （原預設換行）

separator:”,” 分隔接句

Like what you read? Give Buffy Yao a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.