2019年5月29日 星期三

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)


沒有留言:

張貼留言