Upload
kwang-woo-nam
View
47
Download
2
Embed Size (px)
Citation preview
Swift 3 : Collection
군산대학교 컴퓨터정보통신공학부 컴퓨터정보공학전공
남 광 우
Swift 3 Tour and Language Guide by Apple
Collections
• Collection Types• Array, Set, Dictionary• Array 도클래스객체
• C : int arr[5]• Swift : var arr = Array<Int>( repeating : 0, count:5 )
Array
• Array의선언• Array 변수의선언 1
• 빈 Array 변수의선언 2
• 빈 Array 변수의선언 3
C : int[] arrInt;
var arrInt : Array<Int> ;arrInt = Array();
C : int[] arrInt;
var arrInt : [Int];arrInt = [Int]();
C : int arrInt[5];var arrInt = Array<Int>( repeating : 0, count:5 );
C : double arrDbl[3];var arrDbl = Array( repeating:0.0, count:3);
var arrInt: Array<Int> = [3, 4];
var arrInt: [Int] = [3, 4];
• Array의선언과초기화• Array<Int> 형
• [Int] 형
• 예 : String 배열의선언과초기화
• 예 : type의생략
var shoppingList : [String] = [“Eggs”, “Milk”];
var shoppingList = [“Eggs”, “Milk”];
Array
• Array에데이터넣기• Array<Int>(repeating:0, count:0) 로선언한경우
• 예 : 배열데이터수정과내용출력
• Range를이용한갱신
arr[2] = 1;
arr[2…3] = [5,5];
Array
Swift2 : (count:5, repeatedValue:0)
• Array에데이터넣기
• 다음과같이빈 Array를생성한경우
• 데이터추가
• empty array 할당
var arrInt : Array<Int> ;arrInt = Array();
var arrInt : [Int];arrInt = [Int]();
arrInt.append(3);
arrInt = [];
arrInt += [3] ;shoppingList.append(“Flour”);shoppingList += [“Flour”];
Array
• Array에데이터삽입과삭제
• 데이터삽입하기
• 데이터삭제하기
arrInt.insert( 5, at : 0 );
arrInt.remove( at : 4 );
arrInt.removeLast( );
Array
Swift2
• isEmpty• Array 의 empty 상태파악하기
• enumerated• ( index, value) tuple 형태로 enumeration
if arrInt.isEmpty {print( “empty”);
}
for (index, value) in shoppingList.enumerated() {print("Item \(index + 1): \(value)")
}
Array
Set
var letters = Set<Character>()print("letters is of type Set<Character> with \(letters.count) items.")// Prints "letters is of type Set<Character> with 0 items."
• Set의생성
• Set에데이터넣기
letters.insert("a")// letters now contains 1 value of type Characterletters = []// letters is now an empty set, but is still of type Set<Character>
Set
• Set변수와초기화
• Set 초기화
// letters is now an empty set, but is still of type Set<Character>var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]// favoriteGenres has been initialized with three initial items
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
Set
• Set개수세기
• isEmpty
print("I have \(favoriteGenres.count) favorite music genres.")// Prints "I have 3 favorite music genres.
if favoriteGenres.isEmpty {print("As far as music goes, I'm not picky.")
} else {print("I have particular music preferences.")
}// Prints "I have particular music preferences."
• Set삽입과삭제
• contains
favoriteGenres.insert("Jazz")// favoriteGenres now contains 4 items
if let removedGenre = favoriteGenres.remove("Rock") {print("\(removedGenre)? I'm over it.")
} else {print("I never much cared for that.")
}
if favoriteGenres.contains("Funk") {print("I get up on the good foot.")
} else {print("It's too funky in here.")
}// Prints "It's too funky in here."
Set
• Set in For‐Loop
for genre in favoriteGenres {print("\(genre)")
}// Jazz// Hip hop// Classical
for genre in favoriteGenres.sorted() {print("\(genre)")
}// Classical// Hip hop// Jazz
Set
• Set Operation
Set
• Set Operation
let oddDigits: Set = [1, 3, 5, 7, 9]let evenDigits: Set = [0, 2, 4, 6, 8]let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sorted()// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]oddDigits.intersection(evenDigits).sorted()// []oddDigits.subtracting(singleDigitPrimeNumbers).sorted()// [1, 9]oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()// [1, 2, 9]
Set
• Set Operation
let houseAnimals: Set = ["🐶", "🐱"]let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]let cityAnimals: Set = ["🐦", "🐭"]
houseAnimals.isSubset(of: farmAnimals)// truefarmAnimals.isSuperset(of: houseAnimals)// truefarmAnimals.isDisjoint(with: cityAnimals)// true
Set
Dictionary
• Dictionary 생성
• Dictionary에값넣고출력하기
var namesOfIntegers = [Int: String]()// namesOfIntegers is an empty [Int: String] dictionary
nameOfIntegers[3] = "three";for i in nameOfIntegers{
print( "\(i.0) \(i.1) " );}
Dictionary
• Dictionary 생성과초기화
• type 없는생성
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
Dictionary
•데이터갱신
•데이터삭제
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {print("The old value for DUB was \(oldValue).")
}// Prints "The old value for DUB was Dublin."
if let removedValue = airports.removeValue(forKey: "DUB") {print("The removed airport's name is \(removedValue).")
} else {print("The airports dictionary does not contain a value for DUB.")
}// Prints "The removed airport's name is Dublin Airport."
Dictionary
• Iterating (key, value ) tuple
• key의 enumeration
for (airportCode, airportName) in airports {print("\(airportCode): \(airportName)")
}// YYZ: Toronto Pearson// LHR: London Heathrow
for airportCode in airports.keys {print("Airport code: \(airportCode)")
}// Airport code: YYZ// Airport code: LHR
for airportName in airports.values {print("Airport name: \(airportName)")
}// Airport name: Toronto Pearson// Airport name: London Heathrow
Dictionary
• key 또는 value의 array 만들기
let airportCodes = [String](airports.keys)// airportCodes is ["YYZ", "LHR"]
let airportNames = [String](airports.values)// airportNames is ["Toronto Pearson", "London Heathrow"]
실습
• Mac OS X 용으로컴파일하기
실습
실습
•컴파일된Mac OS X 용실행파일만들기
•실행
•실행파일의위치• /Users/사용자이름/Library/Developer/ Xcode/DerivedData/프로젝트이름/Build/Products/Debug
print( “name“);var name = readLine();print( “Hello \(name!)~~~“);