Swift 3 : Collection
군산대학교 컴퓨터정보통신공학부 컴퓨터정보공학전공
남 광 우
kwnam@kunsan.ac.kr
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 Character
letters = []
// 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)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.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!)~~~“);

Swift 3 Programming for iOS : Collection