2019年5月29日 星期三

control Flow

判斷
if...
else if ...
else...

switch

guard ... else

迴圈
(明確知道要執行的次數)
for in

(不知道要執行的次數)
while

(不知道要執行的次數)
repead
while

let names = ["Anna", "Alex", "Brian", "Jack"];
for name in names {
    print("Hello!\(name)");
}
let numberOfLegs = ["spider":8, "ant":6, "cat":4];
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs");
}

for index in 1..<5{
    print(index);
}
let base = 3;
let power = 10;
var answer = 1;

for _ in 1...power {
    answer *= base;
}

let minutes = 60
let minuteInterval = 5
//從0開始,每次+5,到60(不包含60)
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    print(tickMark);
}

//從0開始,每次+5,到60(包含60)
for tickMark in stride(from: 0, through: minutes, by: minuteInterval) {
    print(tickMark);
}

while  判斷 {
 
}
//相當於C的for(int i=25,i>=0;i--)
var finalSquare = 25
while finalSquare >=0 {
    print(finalSquare);
    finalSquare -= 1;
}

finalSquare = 25;
repeat {
    finalSquare -= 1;
} while finalSquare >=0

單向式
if 判斷式 {

}

雙向式 (一定執行其中一個)
if 判斷式 {

} else {

}

多向式(一定執行其中一個)
if 判斷式 {

} else if 判斷式{

} else if 判斷式{

} else {

}

var temperatureInFahrenheit = 30;
if temperatureInFahrenheit <= 32 {
    print("非常冷");
}
temperatureInFahrenheit = 35;
if temperatureInFahrenheit <= 32 {
    print("非常冷");
} else {
    print("不會冷");
}
 temperatureInFahrenheit = 90;
if temperatureInFahrenheit <= 32 {
    print("非常冷");
} else if temperatureInFahrenheit >= 86{
    print("非常熱");
} else {
    print("舒適!")
}
//siwft的switch只會執行其中一個區段,執行完跳出switch!
let someCharacter:Character = "z";
switch someCharacter {
    case "a":
        print("a");
    case "z":
        print("z");
    default:
        print("b~y");
}

let anotherCharacter:Character = "a";
switch anotherCharacter {
    case "a","A":
        print("a,A");
    case "b","B":
        print("b,B");
    default:
        print("其他");
}

//interval Matching
let approximateCount = 62
switch approximateCount {
    case 0:
        print("0");
    case 1..<5:
        print("1~4");
    case 5..<12:
        print("5..11");
    case 12..<100:
        print("12..99");
    case 100..<1000;
        print("100..999");
    default:
        print(">1000");
}
//範圍多值比對
let somePoint = (x:1,y:1);
switch    somePoint {
    case (0,0):
        print("0,0");
    case (_,0):
        print("y=0");
    case (0,_):
        print("x=0");
    case (-2...2,-2...2):
        print("-2...2,-2...2");
    default:
        print("其他");
}
//switch value binding
let anotherPoint = (2,0);
switch anotherPoint {
    case (let x, 0):
        print("y是0,x是\(x)");
    case (0, let y):
        print("x是0,y是\(y)");
    case let (x, y):
        print("x是\(x),y是\(y)");
    //因為一定會執行上方三個區塊其中一個,所以default可以省略!
    /*
    default:
        break;
    */
}
//switch value binding + where
let yetAnotherPoint = (1, -1);
switch yetAnotherPoint {
    //where 後面一定接bool
    case let (x, y) where x == y:
        print("x==y");
    case let (x, y) where x == -y:
        print("x==-y");
    case let (x, y):
        print("x=\(x), y=\(y)");
}

提早離開function
guard ... else,只執行false區段,true時不動作!
guard (false) else {
    false 區段
}
//guard else
func greet(person:[String:String]) {
    guard let name = person["name"] else {
        print("key沒有name");
        return;
    }
    print("Hello!\(name)!");

    gurade let location = person["location"] else {
        print("key沒有location");
        return;
    }
    print("name=\(name),location=\(location)");
}
greet(person: ["name":"John", "location":"Cupertino"]);


collection type

collection type(集合物件)
Array:有順序
Dictionary:沒有順序,key(必須是可以比較大小的(hashable))對應value
set:沒有順序,成員不會重複!hashable(可以比較大小的),Int,Double,Float,Bool,String


資料類型表示法:
陣列:
標準: Array<Int>
簡化:[Int]
var someInts = [Int]();
print(someInts.count); <----0
SomeInts.append(3);
SomeInts.append(4);
SomeInts.append(5);
print(someInts.count); <----3

objective-c
NSMutableArray:可變動(內容)的array
NSArray:不可變動(內容)的array

swift
var Array:可變動
let array:不可變動

var threeDoubles = Array(repeating: 0.0, count:30);
var anotherThreeDouble = Array(repesting: 2.5, count: 3);
var dixDoubles = threeDoubles + anotherThreeDouble;
var shoppingList:[String] = ["Effs", "Milk"];
if shoppingList.isEmpty {
    print("is empty");
} else {
    print("不是空的!有\(shoppingList.count)");
}
shoppingList.append("Flour");
shoppingList += ["Baking Powdwe"];
shoppingList += ["Chocolate Spread", "Cheese","Butter"];
shoppingList[0] = "Six eggs";
shoppingList[4...6];
shoppingList.insert("Maple Syrup", at: 0);
let mapleSyrup = shoppingList.remove(at: 0);

for item in shoppingList {
    print(item);
}

shoppingList.enumerated 傳出tuple (index,item)
for (index,item) in shoppingList.enumerated() {
    print("這個索引編號是\(index),內容是\(item)");
}

資料類型表示法:
Set<Int>
//建立一個空的Set,資料型態是Character,並初始化
var letters = Set<Character>();
print("letters is of type Set<Character> with \(letters.count)");
letters.insert("a");
//清空
letters = [];
//利用陣列值的表示法
var favoriteGenres:Set = ["Rock", "Classical", "Hip hop"];
favoriteGenres.count
favoriteGenres.insert("Jazz");
if favoriteGenres.remove("Rock") == nil {
    print("移除失敗!");
}
if favoriteGenres.contains("Funk") {
    print("有Funk這個值!");
} else {
    print("沒有Funk這個值!");
}
for genre in favoriteGenres {
    print("\(genre)");
}
//一般Set會轉成陣列使用
let sortedGenres = favoriteGenres.sorted();

資料類型表示法:
標準:
Dictionary<String,String>
簡易:
[String:String]
值表示法 ["tw":"Taiwan"];

var namesOfIntegers = [Int:String]();
namesOfIntegers[16] = "sixteen";
//清空
namesOfIntegers = [:];
var airports = [
    "YYZ": "Toronto pearson",
    "DUB": "Dublin"
]
//如果沒有該值,就新增;如果有,就修改!
airports["LHR"] = "London"
airports["LHR"] = "London Heathrow"

//一般的更新法(update())
if let _ =  airports.updateValue("Dublin Airport", forkey: "DUB"){
    //true區段,表示有值
    print("成功!");
} else {
    //false區段得到nil
    print("失敗!");
}
//透過key取出值,會傳出optional type
if let airportName = airports["DUB"] {
    print("DUB的名字是\(airportName)");
} else {
    print("key有錯!");
}
//如果沒有該值,就新增;如果有,就修改!
airports["APL"] = "Apple Internation"
//刪除
airports["APL"] = nil;

for (airportCode, airportName) in airports {
    print("\(airportCode),\(airportName)");
}

for airportCode in airports.keys {
    print(airportCode);
}

for airportName in airports.values {
    print(airportName);
}
//轉陣列
let airportsCodes = [String](airports.keys)
let airportValues = [String](airports.values)


2019年5月27日 星期一

nil 運算子,範圍運算子,for in 迴圈

nil 運算子
正常的type = optional Int ?? 0 <----不明確宣告
let defaultColorName = "red";
var userDefinedColorName:String?;
var colorNameForUser = userDefinedColorName ?? defaultColorName;

範圍運算子
1...5   1,2,3,4,5
1..<5  1,2,3,4
for in 迴圈
for index in 1...5 {
     print(index)
}
let names = ["Anna", "Alex", "Brian", "Jack"];
let count = name.count;
for i in 0..<count {
    names[i];
}
for name in names[2...] {
    print(name);
}
for name in names[...2] {
    print(name);
}

邏輯運算子
!    ---> not
&& ---> and
||    ---> or

let allowedEntry = false;
if !allowedEntry {
    print("Access Denied");
}







2019年5月26日 星期日

optional binding

if let 常數名 = optional type {
     true 區塊
} else {
     false 區塊
}

如果“optional type” 的值不是nil,會自動解開,設定給“常數名”,並執行true區塊,否則就執行false區塊!

let possibleNumber = "123a";
//optional binding
if let convertedNumber = Int(passibleNumber) {
    print(convertedNumber );
} else {
    print("轉換錯誤!!");
}

if let firstNumber = Int("4"), secondNumber = Int("42") {
print(firstNumber);
print(secondNumber);
}