第二天, 基礎語法大家都懂, 大致整理一下
分成Variable, Array, Dictionary, Tuple
For_loop, While_loop
執行看看檢視自己都會不會
//Variable部分
//變數宣告
var x = 2
//加法
x+3
//常數宣告(常數跟變數差別:常數是以後不能變動的值)
let age = 18
//宣告給型態
var intnum:Int = 10
var floatnum:Float = 3.5
//不同型態不能計算, 所以換成同型態
Float (intnum) * floatnum
//字串
var myName = "Jillou"
//字串裡面放變數
var title = "My name is (myName), and my phone number is "0920000000""
//全部大小寫
title.lowercased()
title.uppercased()
//Array部分
/宣告陣列
沒找到值會報錯/
var zooArray = ["one", "two", "three", "four", "five"]
var zooArray2:[String] = ["one", "two", "three", "four", "five"]
zooArray
zooArray[0]
//zooArray[5]
//空陣列宣告
var empty:[Int] = []
var empty2 = Int
//陣列相加
zooArray[0] + zooArray[4]
//陣列大小
zooArray.count
//陣列添加
zooArray.append("tiger")
//陣列插入
zooArray.insert("puppy", at: 1)
//陣列移除
zooArray.remove(at: 3)
//陣列移除第一個
zooArray.removeFirst()
//陣列移除最後一個
zooArray.removeLast()
//陣列翻轉
zooArray.reverse()
//Dictionary部分
/字典宣告(一個key對一個value)
沒找到key會空值nil, 不會報錯/
var dic = ["apple":"32", "banana":"10", "candy":"3"]
var dic2:[String:Int] = ["apple":32, "banana":10, "candy":3]
dic
dic["apple"]
dic["pineapple"]
//從dictionary拿到值的型別是optional(可能有值, 可能沒有值)
var dicType = dic2["candy"]
//把key的value改掉
dic["banana"] = "15"
dic.updateValue("10", forKey: "banana")
//新增key:value
dic["pineapple"] = "100"
dic.updateValue("150", forKey: "grape")
//刪除key:value
dic["candy"] = nil
dic.removeValue(forKey: "pineapple")
//Tuple_Course(元組)部分
//是用小括號包的
var tuple = (1,3,7,5,9,2525,3)
tuple.3
var tuple2 = (3, "HiHi", ["1","2","5"])
tuple2.2[0]
var tuple3 = (apple:"red", banana:"yellow", kiwifruit:"green")
tuple3.banana
tuple3.1
//forloop部分
//陣列表示
var numArray = [2,7,24,13,77,41]
for number in numArray{
print(number)
}
//dictionary表示
//(ikey, ivalue)表示方式就是tuple
var dicNum = ["Bookone":1,"Booktwo":2,"Bookthree":3]
for (ikey, ivalue) in dicNum{
print(ikey + ":" + String(ivalue))
}
//範圍
for number in 5...29{
print(number)
}
//範圍&&不需要用到變數(用底線_代替)
for _ in 3...5{
print("HiHi")
}
//有條件的範圍
for i in 2...15 where i % 3 == 0{
print(i)
}
//whileloop部分
var weight = 0
while weight<=52{
print(weight)
weight += 10
}
//一般while寫法
var nameArray = ["Peter", "Ariel", "Steven", "Winnie"]
var index = 0
while index < nameArray.count{
print(nameArray[index])
index += 1
}
//repeat_while寫法
//就算條件不符合, 也會執行一次
index = 0
repeat{
print(nameArray[index])
index += 1
}while index < nameArray.count