24
Swift 3 : Collection 군산대학교 컴퓨터정보통신공학부 컴퓨터정보공학전공 남광우 [email protected] Swift 3 Tour and Language Guide by Apple

Swft 3 for C Programmers : Collection

Embed Size (px)

Citation preview

Page 1: Swft 3 for C Programmers : Collection

Swift 3 : Collection

군산대학교 컴퓨터정보통신공학부 컴퓨터정보공학전공

남 광 우

[email protected]

Swift 3 Tour and Language Guide by Apple

Page 2: Swft 3 for C Programmers : Collection

Collections

• Collection Types• Array, Set, Dictionary• Array 도클래스객체

• C :   int arr[5]• Swift :  var arr = Array<Int>( repeating : 0, count:5 )

Page 3: Swft 3 for C Programmers : Collection

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);

Page 4: Swft 3 for C Programmers : Collection

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

Page 5: Swft 3 for C Programmers : Collection

• Array에데이터넣기• Array<Int>(repeating:0, count:0) 로선언한경우

• 예 : 배열데이터수정과내용출력

• Range를이용한갱신

arr[2] = 1;

arr[2…3] = [5,5];

Array

Swift2 : (count:5, repeatedValue:0)

Page 6: Swft 3 for C Programmers : Collection

• 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

Page 7: Swft 3 for C Programmers : Collection

• Array에데이터삽입과삭제

• 데이터삽입하기

• 데이터삭제하기

arrInt.insert( 5, at : 0 );

arrInt.remove( at : 4 );

arrInt.removeLast( );

Array

Swift2 

Page 8: Swft 3 for C Programmers : Collection

• 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

Page 9: Swft 3 for C Programmers : Collection

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>

Page 10: Swft 3 for C Programmers : Collection

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"]

Page 11: Swft 3 for C Programmers : Collection

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."

Page 12: Swft 3 for C Programmers : Collection

• 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

Page 13: Swft 3 for C Programmers : Collection

• 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

Page 14: Swft 3 for C Programmers : Collection

• Set Operation

Set

Page 15: Swft 3 for C Programmers : Collection

• 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

Page 16: Swft 3 for C Programmers : Collection

• 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

Page 17: Swft 3 for C Programmers : Collection

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) " );}

Page 18: Swft 3 for C Programmers : Collection

Dictionary

• Dictionary 생성과초기화

• type 없는생성

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

Page 19: Swft 3 for C Programmers : Collection

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."

Page 20: Swft 3 for C Programmers : Collection

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

Page 21: Swft 3 for C Programmers : Collection

Dictionary

• key 또는 value의 array 만들기

let airportCodes = [String](airports.keys)// airportCodes is ["YYZ", "LHR"]

let airportNames = [String](airports.values)// airportNames is ["Toronto Pearson", "London Heathrow"]

Page 22: Swft 3 for C Programmers : Collection

실습

• Mac OS X 용으로컴파일하기

Page 23: Swft 3 for C Programmers : Collection

실습

Page 24: Swft 3 for C Programmers : Collection

실습

•컴파일된Mac OS X 용실행파일만들기

•실행

•실행파일의위치• /Users/사용자이름/Library/Developer/ Xcode/DerivedData/프로젝트이름/Build/Products/Debug

print( “name“);var name = readLine();print( “Hello \(name!)~~~“);