print函數(shù)
print("Hello,world")
?: 默認(rèn)情況下print函數(shù)輸出后會(huì)自動(dòng)換行顶别,如果不希望換行可以通過(guò)指定terminator參數(shù)設(shè)定自己的終止符來(lái)替換掉默認(rèn)的換行符
Naming Constants and Variables (標(biāo)識(shí)符的命名規(guī)則)
- 字母(Unicode字符)、數(shù)字、下劃線(xiàn),數(shù)字不能開(kāi)頭
- 大小寫(xiě)敏感
- 不能使用關(guān)鍵字做標(biāo)識(shí)符
- 駝峰標(biāo)識(shí) - 第一個(gè)單詞全小寫(xiě)以后每個(gè)單詞首字母大寫(xiě)
- 見(jiàn)名知意
?: var用來(lái)定義變量连霉,let用來(lái)定義常量
print("請(qǐng)輸入圓的半徑: ", terminator: "" )
let r = inputDouble()
let perimeter = 2 * M_PI * r
let area = M_PI * r * r
print(String(format: "周長(zhǎng): %.2f", perimeter))
print(String(format: "面積: %.2f", area))
?: 正常情況下表示整數(shù)首選Int, 表示小數(shù)首選Double, 表示字符串首選String, 表示真假首選Bool.
String Interpolation (字符串插值)
print("\\\\(a) + \\\\(b) = \\\\(a + b)")
print("\\\\(a) - \\\\(b) = \\\\(a - b)")
print("\\\\(a) * \\\\(b) = \\\\(a * b)")
print("\\\\(a) / \\\\(b) = \\\\(a / b)")
print("\\\\(a) % \\\\(b) = \\\\(a % b)")
轉(zhuǎn)義字符 - \\n(換行符), \\t(制表符)
print("Hello, World!", terminator: "\\\\n")
print("大家好", terminator: "\\\\t")
print("")
Swift中的運(yùn)算
?: 運(yùn)算符
-算術(shù)運(yùn)算符: + - * / %
-關(guān)系運(yùn)算符: == != > >= < <=
-短路運(yùn)算符: && ||
?: Swift中加減乘除運(yùn)算的左右兩邊類(lèi)型必須一致
let x: Double = 321.99999
print(x / Double(b))
print(Int(x) / b)
?: && - 短路與運(yùn)算(而且) || - 短路或運(yùn)算(或者)
let year = 2000
let c1 = year % 4 == 0 // 四年一閏
let c2 = year % 100 != 0 // 百年不閏
let c3 = year % 400 == 0 // 四百年又閏
if (c1 && c2) || c3 {
print("\\\\(year)年是閏年")
}
else {
print("\\\\(year)年不是閏年")
}
?: 用科學(xué)計(jì)數(shù)法表示小數(shù)
y = 1.23e4
print(y) // 12300.0
y = 1.23e-4
print(y) // 0.000123
?: 忽略不計(jì)
y = 0xAp3
print(y) // 80.0
y = 0x10p-2
print(y) // 4.0
?: 復(fù)合賦值運(yùn)算符
a += b
a -= b
a *= b
a /= b
a %= b
print(a)
?: 元組(tuple) - 用一個(gè)變量或者一個(gè)常量保存多項(xiàng)數(shù)據(jù)信息的類(lèi)型
(x, y) = (y, x) // 用元組交換兩個(gè)變量的值
?: 比較運(yùn)算符 (關(guān)系運(yùn)算符) 產(chǎn)生bool類(lèi)型的值要么是true,要么是false
?: 三元條件運(yùn)算符 -- question ? answer1 : answer2 (問(wèn)號(hào)前面是一個(gè)產(chǎn)生Bool類(lèi)型的變量常量或表達(dá)式,如果其值為true就取冒號(hào)前面的值轰坊,如果其值為False則取冒號(hào)后面的值)
- 三元條件運(yùn)算的?前面一定要加空格!!!
let msg = username == "admin" && password == "123456" ? "登錄成功!!!" : "非法用戶(hù)!!!"
?: 可以使用圓括號(hào)改變運(yùn)算順序
分支語(yǔ)句
?: if - else
- 輸入年和月 輸出這個(gè)月有多少天
print("請(qǐng)輸入年和月用空格隔開(kāi)(例如: 1980 2)")
let year = inputInt()
let month = inputInt()
let day: Int
if month < 1 || month > 12 {
print("瓜西西的")
exit(0) // 程序退出不再執(zhí)行
}
else if month == 2 {
day = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? 29 : 28
}
else if month == 4 || month == 6 || month == 9 || month == 11 {
day = 30
}
else {
day = 31
}
print("\\\\(year)年\\\\(month)月有\(zhòng)\\\(day)天")
- 分段函數(shù)求值
print("x = ", terminator: "")
let x = inputDouble()
let y: Double
if x < -1 {
y = 2 * x - 5
}
else if x <= 1 {
y = 3 * x + 7
}
else {
y = 4 * x - 3
}
print("f(\\\\(x)) = \\\\(y)")
?: switch - case 語(yǔ)句
- 搖色子決定做什么事
let face = Int(arc4random_uniform(6)) + 1
switch face {
case 1:
print("扮鬼臉")
case 2:
print("吻對(duì)方")
case 3:
print("真心話(huà)")
case 4:
print("唱一首")
case 5:
print("聽(tīng)指揮")
case 6:
print("脫一件")
default:
print("色子壞了!!!")
}
- IT從業(yè)人員等級(jí)評(píng)定
print("請(qǐng)輸入你的月薪: ", terminator: "")
let salary = inputInt()
if salary >= 0 {
switch salary {
case 0:
print("你是一個(gè)無(wú)業(yè)游民")
case 1...30000:
print("你是一個(gè)小碼畜")
case 30001...60000:
print("你是一個(gè)小碼奴")
case 60001...100000:
print("你是一個(gè)大碼農(nóng)")
case 100001...200000:
print("你是一個(gè)光榮的IT民工")
case 200001...500000:
print("你是一個(gè)優(yōu)秀的IT工程師")
case 500001..<10000000:
print("你是IT精英")
case 10000000..<100000000:
print("你是IT大哥, 我服")
default:
print("你是頭上有光環(huán)的IT領(lǐng)袖, 求帶")
}
}
else {
print("你丫有病!!!")
}
循環(huán)語(yǔ)句
?: for循環(huán)
- 水仙花數(shù) - 153 = 1^3 + 5^3 + 3^3
func cube(n: Int) -> Int {
return n * n * n
}
for i in 100...999 {
let a = i % 10 // 個(gè)位
let b = i / 10 % 10 // 十位
let c = i / 100 // 百位
if i == cube(a) + cube(b) + cube(c) {
print(i)
}
}
- 猴子吃桃
var sum = 1
for _ in 0..<9 {
sum = (sum + 1) * 2
}
print(sum)
- 求m的n次方(m和n都是正整數(shù))
print("m = ", terminator: "")
let m = inputInt()
print("n = ", terminator: "")
let n = inputInt()
var val = 1.0
for _ in 0..<n {
val *= Double(m)
}
print("\\\\(m)的\\\\(n)次方 = \\\\(val)")
?: while 循環(huán) (有可能一次都不執(zhí)行)
- 求階乘
print("n = ", terminator: "")
let n = inputInt()
var val = 1.0
var i = 2
while i <= n {
val *= Double(i)
i += 1
}
print("\\\\(n)! = \\\\(val)")
- 求1-100之間的偶數(shù)的和
var sum = 0
var i = 2
while i <= 100 {
sum += i
i += 2
}
print(sum)
- 用for循環(huán)求1-100之間的偶數(shù)的和
var sum = 0
for i in 1...100 {
if i % 2 == 0 {
sum += i
}
}
print(sum)
?: repeat - while 循環(huán)(程序至少執(zhí)行一次)
var i = 1
repeat {
print("\\\\(i). Hello, world!")
i += 1
} while i <= 100
?: 分支語(yǔ)句&&循環(huán)語(yǔ)句的重要應(yīng)用
- Craps賭博游戲
func roll() -> Int {
return Int(arc4random_uniform(6)) + 1
}
var money = 1000
repeat {
print("玩家總資產(chǎn): ¥\\\\(money)元")
var debt: Int
repeat {
print("請(qǐng)下注: ", terminator: "")
debt = inputInt()
} while debt <= 0 || debt > money
var needsGoOn = false
let firstPoint = roll() + roll()
print("玩家搖出了\\\\(firstPoint)點(diǎn)")
switch firstPoint {
case 7, 11:
money += debt
print("玩家勝!!!")
case 2, 3, 12:
money -= debt
print("莊家勝!!!")
default:
needsGoOn = true // 游戲繼續(xù)
}
while needsGoOn {
let currentPoint = roll() + roll()
print("玩家搖出了\\\\(currentPoint)點(diǎn)")
if currentPoint == 7 {
money -= debt
print("莊家勝!!!")
needsGoOn = false
}
else if currentPoint == firstPoint {
money += debt
print("玩家勝!!!")
needsGoOn = false
}
} } while money > 0 print("你破產(chǎn)了!!!")
- 百錢(qián)百雞 - GET: 窮舉法(窮盡所有的可能性直到找到正確答案)
for x in 0...20 {
for y in 0...33 {
let z = 100 - x - y
if 5 * x + 3 * y + z / 3 == 100 && z % 3 == 0 {
print("公雞: \\\\(x), 母雞: \\\\(y), 小雞: \\\\(z)")
}
}
}
- 冒泡排序: 兩兩比較, 前面的元素比后面的元素大就交換位置
var array = [29, 98, 35, 12, 47, 66, 53, 79]
for i in 0..<array.count - 1 {
var swapped = false
for j in 0..<array.count - 1 - i {
if array[j] > array[j + 1] {
(array[j], array[j + 1]) = (array[j + 1], array[j])
swapped = true
}
}
if !swapped {
break
}
}
print(array)
- 簡(jiǎn)單選擇排序: 每次從剩下元素中找最小的元素放到對(duì)應(yīng)的位置
var array = [29, 98, 35, 12, 47, 66, 53, 79]
for i in 0..<array.count - 1 {
var minIndex = i
for j in i + 1..<array.count {
if array[j] < array[minIndex] {
minIndex = j
}
}
(array[i], array[minIndex]) = (array[minIndex], array[i])
}
print(array)
數(shù)組
?: 創(chuàng)建數(shù)組
var array1 = [String]()
var array2: [String] = []
var array3 = ["apple", "grape", "banana", "apple", "orange"]
var array4 = [String](count: 100, repeatedValue: "")
?: 獲取數(shù)組元素個(gè)數(shù)
print(array1.count)
print(array2.count)
print(array3.count)
print(array4.count)
?: 對(duì)數(shù)組中的元素進(jìn)行遍歷
for index in 0..<array3.count {
// []是對(duì)數(shù)組進(jìn)行下標(biāo)運(yùn)算(取出指定位置的元素)
print(array3[index])
if index == 1 {
array3[index] = "litch"
}
}
print(array3)
?: 向數(shù)組中添加元素
array1 += ["strawberry"] // +=即在數(shù)組的最后加入相當(dāng)于.append
array1.append("pear")
array1.insert("waxberry", atIndex: 0) // .insert即在數(shù)組的指定位置加入
array1.insert("watermelon", atIndex: 2)
array1.insert("lemon", atIndex: array1.count) //在這個(gè)數(shù)組的最后加入
print(array1)
?: 從數(shù)組中刪除元素
array1.removeAtIndex(2) // 指定位置刪除
print(array1)
array1.removeFirst() // 刪除第一個(gè)
print(array1)
array1.removeAll() // 全部刪除
print(array1)
//array5.removeAll() 全部刪除
//array5.removeAll(keepCapacity: <#T##Bool#>) 只刪除元素不回收空間
//array5.removeAtIndex(2) 刪除指定位置的元素
//array5.removeRange(0...2)//刪除一個(gè)范圍內(nèi)的
?: 數(shù)組的復(fù)制
var array5 = array3 // 復(fù)制數(shù)組
array5[0] = "pitaya" // 數(shù)組的0號(hào)位置元素替換為"pitaya"
print(array3)
print(array5)
var array6 = array3[1...3] // 復(fù)制數(shù)組的一部分
print(array6)
?: 數(shù)組的+運(yùn)算
let array7 = array1 + array3
print(array7) // 元素排列為 - 先排列array1的元素再排列array3的元素
?: 只讀循環(huán)(在循環(huán)過(guò)程中不能修改數(shù)組元素)
for str in array3 {
print(str)
}