SlideShare una empresa de Scribd logo
1 de 29
Descargar para leer sin conexión
Swift 3 :
Subscript, Init, Type Casting
군산대학교 컴퓨터정보통신공학부 컴퓨터정보공학전공
남 광 우
kwnam@kunsan.ac.kr
Swift 3 Tour and Language Guide by Apple
꼼꼼한 재은씨의 Swift 2 프로그래밍
Initialization
• init() 을 이용한 초기화
• Stored Properties 초기화
• Initializer
• 초기화 예
init() {
// 초기화 구문
}
struct Fahrenheit {
var temperature: Double
init() {
temperature = 32.0
}
}
var f = Fahrenheit()
print("The default temperature is (f.temperature)° Fahrenheit")
// Prints "The default temperature is 32.0° Fahrenheit"
Initialization
• Customizing Initialization
• 사용
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit ‐ 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin ‐ 273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0
Initialization
• Parameter Name과 Argument Label
• 사용
struct Color {
let red, green, blue: Double
init(red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
init(white: Double) {
red   = white
green = white
blue  = white
}
}
let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)
let halfGray = Color(white: 0.5)
Initialization
• Parameter Name without Argument Label
• 사용
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit ‐ 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin ‐ 273.15
}
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
let bodyTemperature = Celsius(37.0)
// bodyTemperature.temperatureInCelsius is 37.0
Initialization
• Optional Property 타입
• optional 타입은 default로 nil 설정
• 사용
class SurveyQuestion {
var text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
// Prints "Do you like cheese?"
cheeseQuestion.response = "Yes, I do like cheese."
Initialization
• 초기화 동안 상수 초기화
• 예
class SurveyQuestion {
let text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let beetsQuestion = SurveyQuestion(text: "How about beets?")
beetsQuestion.ask()
// Prints "How about beets?"
beetsQuestion.response = "I also like beets. (But not with 
cheese.)"
초기화 후 변경 불가
Initialization
• Default Property
• Default Initializer
• init이 없으면 default 값으로 설정
struct Fahrenheit {
var temperature = 32.0
}
class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()
Initialization
• Struct를 위한 Memberwise Initializer
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
Initialization
• 대표 Initializer 를 이용한 초기화
struct Rect {
var origin = Point()
var size = Size()
init() {}
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
init(center: Point, size: Size) {
let originX = center.x ‐ (size.width / 2)
let originY = center.y ‐ (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
} struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
Initialization
• Initializer Delegation 이용한 초기화(계속)
• () 사용  
 
 
 
• (origin, size) 
 
 
 
• (center, size) 
 
 
 
 
let basicRect = Rect()
// basicRect's origin is (0.0, 0.0) and its size is (0.0, 0.0)
let originRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
// originRect's origin is (2.0, 2.0) and its size is (5.0, 5.0)
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)
Class Inheritance와 초기화
• Designated Initializer와 Convenience Initializer
• Designated Initializer 
 
 
 
 
• Convenience Initializer 
 
 
 
 
init( parameters )  {
}
convenience init( parameters )  {
}
Class Inheritance와 초기화
class Vehicle {
var numberOfWheels = 0
var description: String {
return "(numberOfWheels) wheel(s)"
}
}
let vehicle = Vehicle()
print("Vehicle: (vehicle.description)")
// Vehicle: 0 wheel(s)
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
• Initializer 예 
 
 
 
Class Inheritance와 초기화
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
let namedMeat = Food(name: "Bacon")
// namedMeat's name is "Bacon"
let mysteryMeat = Food()
// mysteryMeat's name is "[Unnamed]"
• Initializer 예
 
 
 
 
 
 
• 사용 
 
 
 
Class Inheritance와 초기화
• Initializer 상속의 예
 
 
 
 
 
 
 
 
 
 
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity: 1)
}
}
Class Inheritance와 초기화
• Initializer 상속의 예
 
 
 
 
 
 
 
 
 
 
class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "(quantity) x (name)"
output += purchased ? " ✔" : " ✘"
return output
}
}
Class Inheritance와 초기화
• Initializer 상속의 예
 
 
 
 
 
 
 
 
 
 
var breakfastList = [
ShoppingListItem(),
ShoppingListItem(name: "Bacon"),
ShoppingListItem(name: "Eggs", quantity: 6),
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
print(item.description)
}
// 1 x Orange juice ✔
// 1 x Bacon ✘
// 6 x Eggs ✘
Failable Initializer
• ? : Failable Init() 
 
 
 
 
• 사용 
 
 
 
 
 
 
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}
let someCreature = Animal(species: "Giraffe")
if let giraffe = someCreature {
print("An animal was initialized with a species of (giraffe.species)")
}
if  someCreature == nil {
print("The anonymous creature could not be initialized")
}
Failable Initializer for Enum
• ? : Failable Init() for Enum 
 
 
 
 
 
 
 
 
 
 
 
enum TemperatureUnit {
case kelvin, celsius, fahrenheit
init?(symbol: Character) {
switch symbol {
case "K":
self = .kelvin
case "C":
self = .celsius
case "F":
self = .fahrenheit
default:
return nil
}
}
} let fahrenheitUnit = TemperatureUnit(symbol: "F")
if fahrenheitUnit != nil {
print("This is a defined temperature unit, so initialization succeeded.")
}
let unknownUnit = TemperatureUnit(symbol: "X")
if unknownUnit == nil {
print("This is not a defined temperature unit, so initialization failed.")
}
Failable Initializer for Enum
• ? : Failable Init() for Enum with Raw 
 
 
 
 
 
 
 
 
 
 
 
enum TemperatureUnit: Character {
case kelvin = "K", celsius = "C", fahrenheit = "F"
}
let fahrenheitUnit = TemperatureUnit(rawValue: "F")
if fahrenheitUnit != nil {
print("This is a defined temperature unit, so initialization succeeded.")
}
// Prints "This is a defined temperature unit, so initialization succeeded."
let unknownUnit = TemperatureUnit(rawValue: "X")
if unknownUnit == nil {
print("This is not a defined temperature unit, so initialization failed.")
}
// Prints "This is not a defined temperature unit, so initialization failed."
Failable Initializer 상속
• Overriding 
 
 
 
 
 
 
 
 
 
 
 
class Document {
var name: String?
// this initializer creates a document with a nil name value
init() {}
// this initializer creates a document with a nonempty name value
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
}
}
class AutomaticallyNamedDocument: Document {
override init() {
super.init()
self.name = "[Untitled]"
}
override init(name: String) {
super.init()
if name.isEmpty {
self.name = "[Untitled]"
} else {
self.name = name
}
}
}
Closure로 초기화
• 형식 
 
 
 
 
 
 
 
 
 
 
 
struct Chessboard {
let boardColors: [Bool] = {
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...8 {
for j in 1...8 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}()
func squareIsBlackAt(row: Int, column: Int) ‐> Bool {
return boardColors[(row * 8) + column]
}
}
Deinitialization
• 형식
 
 
• Bank/Player 
 
 
 
 
 
 
 
deinit {
// perform the deinitialization
}
class Bank {
static var coinsInBank = 10_000
static func distribute(coins numberOfCoinsRequested: Int) ‐> Int {
let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
coinsInBank ‐= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receive(coins: Int) {
coinsInBank += coins
}
}
Deinitialization
• Bank/Player
• Player는 종료되면 가진 coin을 반환 ‐> deinit 
 
 
class Player {
var coinsInPurse: Int
init(coins: Int) {
coinsInPurse = Bank.distribute(coins: coins)
}
func win(coins: Int) {
coinsInPurse += Bank.distribute(coins: coins)
}
deinit {
Bank.receive(coins: coinsInPurse)
}
}
Deinitialization
• Bank/Player 사용
• win
• player 종료되며 coin 반환
 
 
var playerOne: Player? = Player(coins: 100)
print("A new player has joined the game with (playerOne!.coinsInPurse) coins")
print("There are now (Bank.coinsInBank) coins left in the bank")
playerOne!.win(coins: 2_000)
print("PlayerOne won 2000 coins & now has (playerOne!.coinsInPurse) coins")
print("The bank now only has (Bank.coinsInBank) coins left")
playerOne = nil
print("PlayerOne has left the game")
print("The bank now has (Bank.coinsInBank) coins")
Subscript
• [ ] 를 이용한 컬렉션 접근
• 컬렉션, 리스트, 배열 등의 항목을 [ ] 형태로 접근
• [index] 형태 사용을 위해 subscript 정의 필요
• index로 string도 가능
• read‐only computed properties 인 경우
subscript(index:Int) ‐> Int {
get {
// 항목에 대한 접근 처리
}
set(newValue) {
// newValue에 대한 처리
}
}
subscript(index:Int) ‐> Int {
// 항목에 대한 접근 처리
}
Subscript
• 예 : subscript 정의
• 예 : subscript 사용
struct TimesTable {
let multiplier: Int
subscript(index: Int) ‐> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is (threeTimesTable[6])")
// Prints "six times three is 18"
Subscript
• 예 : Matrix의 Subscript 구현
• Matrix 선언
• Matrix에 데이터 넣기
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
Subscript
• 예 : Matrix의 Subscript 구현
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) ‐> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) ‐> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}

Más contenido relacionado

La actualidad más candente

スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたスマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
Taro Matsuzawa
 

La actualidad más candente (20)

TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando CoroutinesTDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival Guide
 
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
 
Spockを使おう!
Spockを使おう!Spockを使おう!
Spockを使おう!
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
The Ring programming language version 1.9 book - Part 32 of 210
The Ring programming language version 1.9 book - Part 32 of 210The Ring programming language version 1.9 book - Part 32 of 210
The Ring programming language version 1.9 book - Part 32 of 210
 
Programação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesProgramação assíncrona utilizando Coroutines
Programação assíncrona utilizando Coroutines
 
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたスマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
 
oop objects_classes
oop objects_classesoop objects_classes
oop objects_classes
 
The Ring programming language version 1.5.3 book - Part 19 of 194
The Ring programming language version 1.5.3 book - Part 19 of 194The Ring programming language version 1.5.3 book - Part 19 of 194
The Ring programming language version 1.5.3 book - Part 19 of 194
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
Grammarware Memes
Grammarware MemesGrammarware Memes
Grammarware Memes
 
openFrameworks 007 - utils
openFrameworks 007 - utilsopenFrameworks 007 - utils
openFrameworks 007 - utils
 
Pig Introduction to Pig
Pig Introduction to PigPig Introduction to Pig
Pig Introduction to Pig
 
The Ring programming language version 1.6 book - Part 36 of 189
The Ring programming language version 1.6 book - Part 36 of 189The Ring programming language version 1.6 book - Part 36 of 189
The Ring programming language version 1.6 book - Part 36 of 189
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
C++ 11 usage experience
C++ 11 usage experienceC++ 11 usage experience
C++ 11 usage experience
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 

Destacado

Destacado (20)

[공간정보시스템 개론] L04 항공사진의 이해
[공간정보시스템 개론] L04 항공사진의 이해[공간정보시스템 개론] L04 항공사진의 이해
[공간정보시스템 개론] L04 항공사진의 이해
 
[공간정보시스템 개론] L08 gnss의 개념과 활용
[공간정보시스템 개론] L08 gnss의 개념과 활용[공간정보시스템 개론] L08 gnss의 개념과 활용
[공간정보시스템 개론] L08 gnss의 개념과 활용
 
[공간정보시스템 개론] L05 우리나라의 수치지도
[공간정보시스템 개론] L05 우리나라의 수치지도[공간정보시스템 개론] L05 우리나라의 수치지도
[공간정보시스템 개론] L05 우리나라의 수치지도
 
[공간정보시스템 개론] L06 GIS의 이해
[공간정보시스템 개론] L06 GIS의 이해[공간정보시스템 개론] L06 GIS의 이해
[공간정보시스템 개론] L06 GIS의 이해
 
Swift 3 Programming for iOS: error handling
Swift 3 Programming for iOS: error handlingSwift 3 Programming for iOS: error handling
Swift 3 Programming for iOS: error handling
 
Swift 3 Programming for iOS : Enumeration
Swift 3 Programming for iOS : EnumerationSwift 3 Programming for iOS : Enumeration
Swift 3 Programming for iOS : Enumeration
 
Swift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structureSwift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structure
 
Swift 3 Programming for iOS: Function
Swift 3 Programming for iOS: FunctionSwift 3 Programming for iOS: Function
Swift 3 Programming for iOS: Function
 
Swift 3 Programming for iOS : Closure
Swift 3 Programming for iOS  : ClosureSwift 3 Programming for iOS  : Closure
Swift 3 Programming for iOS : Closure
 
Hacker News
Hacker NewsHacker News
Hacker News
 
[공간정보시스템 개론] L07 원격탐사의 개념과 활용
[공간정보시스템 개론] L07 원격탐사의 개념과 활용[공간정보시스템 개론] L07 원격탐사의 개념과 활용
[공간정보시스템 개론] L07 원격탐사의 개념과 활용
 
Support Vector Machines
Support Vector MachinesSupport Vector Machines
Support Vector Machines
 
[공간정보시스템 개론] L12 공간정보분석
[공간정보시스템 개론] L12 공간정보분석[공간정보시스템 개론] L12 공간정보분석
[공간정보시스템 개론] L12 공간정보분석
 
[공간정보시스템 개론] L11 공간정보의 구축
[공간정보시스템 개론] L11 공간정보의 구축[공간정보시스템 개론] L11 공간정보의 구축
[공간정보시스템 개론] L11 공간정보의 구축
 
[공간정보시스템 개론] L01 공간정보시스템개요
[공간정보시스템 개론] L01 공간정보시스템개요[공간정보시스템 개론] L01 공간정보시스템개요
[공간정보시스템 개론] L01 공간정보시스템개요
 
[공간정보시스템 개론] L03 지구의형상과좌표체계
[공간정보시스템 개론] L03 지구의형상과좌표체계[공간정보시스템 개론] L03 지구의형상과좌표체계
[공간정보시스템 개론] L03 지구의형상과좌표체계
 
[공간정보시스템 개론] L09 공간 데이터 모델
[공간정보시스템 개론] L09 공간 데이터 모델[공간정보시스템 개론] L09 공간 데이터 모델
[공간정보시스템 개론] L09 공간 데이터 모델
 
[공간정보시스템 개론] L10 수치표고모델
[공간정보시스템 개론] L10 수치표고모델[공간정보시스템 개론] L10 수치표고모델
[공간정보시스템 개론] L10 수치표고모델
 
[공간정보시스템 개론] L02 공간정보와 지리정보
[공간정보시스템 개론] L02 공간정보와 지리정보[공간정보시스템 개론] L02 공간정보와 지리정보
[공간정보시스템 개론] L02 공간정보와 지리정보
 
Swift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extensionSwift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extension
 

Similar a Swift 3 Programming for iOS : subscript init

服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
Qiangning Hong
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passage
Erik Rose
 

Similar a Swift 3 Programming for iOS : subscript init (20)

Structures
StructuresStructures
Structures
 
Android Automated Testing
Android Automated TestingAndroid Automated Testing
Android Automated Testing
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizations
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack Support
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196
 
Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into Swift
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03
 
The Ring programming language version 1.6 book - Part 15 of 189
The Ring programming language version 1.6 book - Part 15 of 189The Ring programming language version 1.6 book - Part 15 of 189
The Ring programming language version 1.6 book - Part 15 of 189
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swift
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passage
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185
 

Más de Kwang Woo NAM

Más de Kwang Woo NAM (11)

메타버스시대의_디지털트윈과_지역성v01.pdf
메타버스시대의_디지털트윈과_지역성v01.pdf메타버스시대의_디지털트윈과_지역성v01.pdf
메타버스시대의_디지털트윈과_지역성v01.pdf
 
해양디지털트윈v02.pdf
해양디지털트윈v02.pdf해양디지털트윈v02.pdf
해양디지털트윈v02.pdf
 
Moving objects media data computing(2019)
Moving objects media data computing(2019)Moving objects media data computing(2019)
Moving objects media data computing(2019)
 
Moving Objects and Spatial Data Computing
Moving Objects and Spatial Data ComputingMoving Objects and Spatial Data Computing
Moving Objects and Spatial Data Computing
 
세월호/ 타이타닉호 사고의 빅 데이터 방법론적 분석
세월호/ 타이타닉호 사고의 빅 데이터 방법론적 분석세월호/ 타이타닉호 사고의 빅 데이터 방법론적 분석
세월호/ 타이타닉호 사고의 빅 데이터 방법론적 분석
 
Swift 3 Programming for iOS : Collection
Swift 3 Programming for iOS : CollectionSwift 3 Programming for iOS : Collection
Swift 3 Programming for iOS : Collection
 
Swift 3 Programming for iOS : Control flow
Swift 3 Programming for iOS : Control flowSwift 3 Programming for iOS : Control flow
Swift 3 Programming for iOS : Control flow
 
Swift 3 Programming for iOS : data type
Swift 3 Programming for iOS : data typeSwift 3 Programming for iOS : data type
Swift 3 Programming for iOS : data type
 
Swift 3 Programming for iOS
Swift 3 Programming for iOSSwift 3 Programming for iOS
Swift 3 Programming for iOS
 
집단지성 프로그래밍 08-가격모델링
집단지성 프로그래밍 08-가격모델링집단지성 프로그래밍 08-가격모델링
집단지성 프로그래밍 08-가격모델링
 
집단지성 프로그래밍 07-고급 분류 기법-커널 기법과 svm-01
집단지성 프로그래밍 07-고급 분류 기법-커널 기법과 svm-01집단지성 프로그래밍 07-고급 분류 기법-커널 기법과 svm-01
집단지성 프로그래밍 07-고급 분류 기법-커널 기법과 svm-01
 

Último

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Último (20)

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 

Swift 3 Programming for iOS : subscript init

  • 1. Swift 3 : Subscript, Init, Type Casting 군산대학교 컴퓨터정보통신공학부 컴퓨터정보공학전공 남 광 우 kwnam@kunsan.ac.kr Swift 3 Tour and Language Guide by Apple 꼼꼼한 재은씨의 Swift 2 프로그래밍
  • 2. Initialization • init() 을 이용한 초기화 • Stored Properties 초기화 • Initializer • 초기화 예 init() { // 초기화 구문 } struct Fahrenheit { var temperature: Double init() { temperature = 32.0 } } var f = Fahrenheit() print("The default temperature is (f.temperature)° Fahrenheit") // Prints "The default temperature is 32.0° Fahrenheit"
  • 3. Initialization • Customizing Initialization • 사용 struct Celsius { var temperatureInCelsius: Double init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit ‐ 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin ‐ 273.15 } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) // boilingPointOfWater.temperatureInCelsius is 100.0 let freezingPointOfWater = Celsius(fromKelvin: 273.15) // freezingPointOfWater.temperatureInCelsius is 0.0
  • 4. Initialization • Parameter Name과 Argument Label • 사용 struct Color { let red, green, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } init(white: Double) { red   = white green = white blue  = white } } let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) let halfGray = Color(white: 0.5)
  • 5. Initialization • Parameter Name without Argument Label • 사용 struct Celsius { var temperatureInCelsius: Double init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit ‐ 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin ‐ 273.15 } init(_ celsius: Double) { temperatureInCelsius = celsius } } let bodyTemperature = Celsius(37.0) // bodyTemperature.temperatureInCelsius is 37.0
  • 6. Initialization • Optional Property 타입 • optional 타입은 default로 nil 설정 • 사용 class SurveyQuestion { var text: String var response: String? init(text: String) { self.text = text } func ask() { print(text) } } let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?") cheeseQuestion.ask() // Prints "Do you like cheese?" cheeseQuestion.response = "Yes, I do like cheese."
  • 7. Initialization • 초기화 동안 상수 초기화 • 예 class SurveyQuestion { let text: String var response: String? init(text: String) { self.text = text } func ask() { print(text) } } let beetsQuestion = SurveyQuestion(text: "How about beets?") beetsQuestion.ask() // Prints "How about beets?" beetsQuestion.response = "I also like beets. (But not with  cheese.)" 초기화 후 변경 불가
  • 8. Initialization • Default Property • Default Initializer • init이 없으면 default 값으로 설정 struct Fahrenheit { var temperature = 32.0 } class ShoppingListItem { var name: String? var quantity = 1 var purchased = false } var item = ShoppingListItem()
  • 9. Initialization • Struct를 위한 Memberwise Initializer struct Size { var width = 0.0, height = 0.0 } let twoByTwo = Size(width: 2.0, height: 2.0)
  • 10. Initialization • 대표 Initializer 를 이용한 초기화 struct Rect { var origin = Point() var size = Size() init() {} init(origin: Point, size: Size) { self.origin = origin self.size = size } init(center: Point, size: Size) { let originX = center.x ‐ (size.width / 2) let originY = center.y ‐ (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 }
  • 11. Initialization • Initializer Delegation 이용한 초기화(계속) • () 사용         • (origin, size)        • (center, size)          let basicRect = Rect() // basicRect's origin is (0.0, 0.0) and its size is (0.0, 0.0) let originRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) // originRect's origin is (2.0, 2.0) and its size is (5.0, 5.0) let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)
  • 12. Class Inheritance와 초기화 • Designated Initializer와 Convenience Initializer • Designated Initializer          • Convenience Initializer          init( parameters )  { } convenience init( parameters )  { }
  • 13. Class Inheritance와 초기화 class Vehicle { var numberOfWheels = 0 var description: String { return "(numberOfWheels) wheel(s)" } } let vehicle = Vehicle() print("Vehicle: (vehicle.description)") // Vehicle: 0 wheel(s) class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } • Initializer 예       
  • 14. Class Inheritance와 초기화 class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } let namedMeat = Food(name: "Bacon") // namedMeat's name is "Bacon" let mysteryMeat = Food() // mysteryMeat's name is "[Unnamed]" • Initializer 예             • 사용       
  • 15. Class Inheritance와 초기화 • Initializer 상속의 예                     class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { self.init(name: name, quantity: 1) } }
  • 16. Class Inheritance와 초기화 • Initializer 상속의 예                     class ShoppingListItem: RecipeIngredient { var purchased = false var description: String { var output = "(quantity) x (name)" output += purchased ? " ✔" : " ✘" return output } }
  • 17. Class Inheritance와 초기화 • Initializer 상속의 예                     var breakfastList = [ ShoppingListItem(), ShoppingListItem(name: "Bacon"), ShoppingListItem(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } // 1 x Orange juice ✔ // 1 x Bacon ✘ // 6 x Eggs ✘
  • 18. Failable Initializer • ? : Failable Init()          • 사용              struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } let someCreature = Animal(species: "Giraffe") if let giraffe = someCreature { print("An animal was initialized with a species of (giraffe.species)") } if  someCreature == nil { print("The anonymous creature could not be initialized") }
  • 19. Failable Initializer for Enum • ? : Failable Init() for Enum                        enum TemperatureUnit { case kelvin, celsius, fahrenheit init?(symbol: Character) { switch symbol { case "K": self = .kelvin case "C": self = .celsius case "F": self = .fahrenheit default: return nil } } } let fahrenheitUnit = TemperatureUnit(symbol: "F") if fahrenheitUnit != nil { print("This is a defined temperature unit, so initialization succeeded.") } let unknownUnit = TemperatureUnit(symbol: "X") if unknownUnit == nil { print("This is not a defined temperature unit, so initialization failed.") }
  • 20. Failable Initializer for Enum • ? : Failable Init() for Enum with Raw                        enum TemperatureUnit: Character { case kelvin = "K", celsius = "C", fahrenheit = "F" } let fahrenheitUnit = TemperatureUnit(rawValue: "F") if fahrenheitUnit != nil { print("This is a defined temperature unit, so initialization succeeded.") } // Prints "This is a defined temperature unit, so initialization succeeded." let unknownUnit = TemperatureUnit(rawValue: "X") if unknownUnit == nil { print("This is not a defined temperature unit, so initialization failed.") } // Prints "This is not a defined temperature unit, so initialization failed."
  • 21. Failable Initializer 상속 • Overriding                        class Document { var name: String? // this initializer creates a document with a nil name value init() {} // this initializer creates a document with a nonempty name value init?(name: String) { if name.isEmpty { return nil } self.name = name } } class AutomaticallyNamedDocument: Document { override init() { super.init() self.name = "[Untitled]" } override init(name: String) { super.init() if name.isEmpty { self.name = "[Untitled]" } else { self.name = name } } }
  • 22. Closure로 초기화 • 형식                        struct Chessboard { let boardColors: [Bool] = { var temporaryBoard = [Bool]() var isBlack = false for i in 1...8 { for j in 1...8 { temporaryBoard.append(isBlack) isBlack = !isBlack } isBlack = !isBlack } return temporaryBoard }() func squareIsBlackAt(row: Int, column: Int) ‐> Bool { return boardColors[(row * 8) + column] } }
  • 23. Deinitialization • 형식     • Bank/Player                deinit { // perform the deinitialization } class Bank { static var coinsInBank = 10_000 static func distribute(coins numberOfCoinsRequested: Int) ‐> Int { let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank) coinsInBank ‐= numberOfCoinsToVend return numberOfCoinsToVend } static func receive(coins: Int) { coinsInBank += coins } }
  • 24. Deinitialization • Bank/Player • Player는 종료되면 가진 coin을 반환 ‐> deinit      class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.distribute(coins: coins) } func win(coins: Int) { coinsInPurse += Bank.distribute(coins: coins) } deinit { Bank.receive(coins: coinsInPurse) } }
  • 25. Deinitialization • Bank/Player 사용 • win • player 종료되며 coin 반환     var playerOne: Player? = Player(coins: 100) print("A new player has joined the game with (playerOne!.coinsInPurse) coins") print("There are now (Bank.coinsInBank) coins left in the bank") playerOne!.win(coins: 2_000) print("PlayerOne won 2000 coins & now has (playerOne!.coinsInPurse) coins") print("The bank now only has (Bank.coinsInBank) coins left") playerOne = nil print("PlayerOne has left the game") print("The bank now has (Bank.coinsInBank) coins")
  • 26. Subscript • [ ] 를 이용한 컬렉션 접근 • 컬렉션, 리스트, 배열 등의 항목을 [ ] 형태로 접근 • [index] 형태 사용을 위해 subscript 정의 필요 • index로 string도 가능 • read‐only computed properties 인 경우 subscript(index:Int) ‐> Int { get { // 항목에 대한 접근 처리 } set(newValue) { // newValue에 대한 처리 } } subscript(index:Int) ‐> Int { // 항목에 대한 접근 처리 }
  • 27. Subscript • 예 : subscript 정의 • 예 : subscript 사용 struct TimesTable { let multiplier: Int subscript(index: Int) ‐> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print("six times three is (threeTimesTable[6])") // Prints "six times three is 18"
  • 28. Subscript • 예 : Matrix의 Subscript 구현 • Matrix 선언 • Matrix에 데이터 넣기 var matrix = Matrix(rows: 2, columns: 2) matrix[0, 1] = 1.5 matrix[1, 0] = 3.2
  • 29. Subscript • 예 : Matrix의 Subscript 구현 struct Matrix { let rows: Int, columns: Int var grid: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns grid = Array(repeating: 0.0, count: rows * columns) } func indexIsValid(row: Int, column: Int) ‐> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } subscript(row: Int, column: Int) ‐> Double { get { assert(indexIsValid(row: row, column: column), "Index out of range") return grid[(row * columns) + column] } set { assert(indexIsValid(row: row, column: column), "Index out of range") grid[(row * columns) + column] = newValue } } }