SlideShare a Scribd company logo
NHN	NEXT	Eunjoo	Im
Swift3
Subscript
Inheritance
Initialization
NHN NEXT

Swift3 Sutdy
NHN	NEXT	Eunjoo	Im
Subscript

소개
▪ Class, Structure, Enumeration의 subscript라는 메서
드로 정의해서 collection 등의 멤버에 쉽게 접근할 수 있음

▪ index를 통해 쉽게 값을 저장하거나 읽을 수 있음 

ex) someArray[index], someDicitonary[key]

▪ 한 대상에 대해 다수의 subscript를 만들 수 있음

▪ 예약어이므로 func를 쓸 필요 없음
출처: Apple Inc. The Swift Programming Language (Swift 3)
subscript(index: Int) -> Int {

get {

// 원하는 subscript 값을 return

}

set(newValue) {

// 원하는 subscript 값을 설정

}

}
NHN	NEXT	Eunjoo	Im
Subscript

기본 문법(1)
▪ 기본 매개변수 newValue: 생략 가능, 새 이름 설정 가능

▪ 매개 변수는 여러 개도 설정 가능 

▪ read-only 프로퍼티에 대해서는 get 키워드 생략 가능
subscript(index: Int) -> Int {

}
struct TimesTable {

let multiplier: Int

subscript(index: Int) -> Int {

return multiplier * index

}

}

let threeTimesTable = TimesTable(multiplier: 3)

print("(threeTimesTable[6])")

// "18"
출처: Apple Inc. The Swift Programming Language (Swift 3)
어떤	값이	찍힐까요?
NHN	NEXT	Eunjoo	Im
Subscript

기본 문법(2)
▪ 기본 매개변수 newValue: 생략 가능, 새 이름 설정 가능

▪ 매개 변수는 여러 개도 설정 가능 

▪ read-only 프로퍼티에 대해서는 get 키워드 생략 가능
subscript(index: Int) -> Int {

}
struct TimesTable {

let multiplier: Int

subscript(index: Int) -> Int {

return multiplier * index

}

}

let threeTimesTable = TimesTable(multiplier: 3)

print("(threeTimesTable[6])")

// "18"
출처: Apple Inc. The Swift Programming Language (Swift 3)
NHN	NEXT	Eunjoo	Im
Subscript

사용예
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ collection, list, sequence의 멤버에 쉽게 엑세스하는 방
법으로 사용

▪ Dictionary에 subscript를 설정해서 인스턴스에 저장된
값을 가져올 수 있음

▪ Dictionary의 키 타입에 맞는 키를 사용해서 값을 설정할
수 있음

▪ 상위 예제의 다리 숫자는 Int?로 Optional Int임

▪ 모든 Key가 Value를 가지지 않아도 됨

▪ Value를 삭제하려면 nil로 설정
var numberOfLeg = ["spider": 8, "ant": 6, "cat": 4]

numberOfLeg[“bird"] = 2
NHN	NEXT	Eunjoo	Im
Subscript

옵션(1)
출처: Apple Inc. The Swift Programming Language (Swift 3)
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

}

}

}
matrix[0, 1] = 1.5

matrix[1, 0] = 3.2
var matrix = Matrix(rows: 2, columns: 2)
어떤	행렬이	될까요?
NHN	NEXT	Eunjoo	Im
Subscript

옵션(2)
출처: Apple Inc. The Swift Programming Language (Swift 3)
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

}

}

}
matrix[0, 1] = 1.5

matrix[1, 0] = 3.2
var matrix = Matrix(rows: 2, columns: 2)
NHN	NEXT	Eunjoo	Im
Inheritance

소개
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ Class는 메서드, 프로퍼티 등을 다른 Class로부터 상속받을
수 있음

▪ 상속한 Class는 superclass, 상속받은 Class는 subclass

▪ Class를 다른 타입과 구분짓는 특징

▪ 상속받은 메서드, 프로퍼티, subscript를 호출하거나,
overriding해서 사용할 수 있음

▪ 상속받은 프로퍼티에 property observer를 추가해서 프로
퍼티가 수정된 것을 파악할 수 있음

(단, Stored나 computed 프로퍼티로 정의돼야 함)

▪ subclass를 다시 subclassing할 수도 있음

▪ final을 사용해서 메서드, 프로퍼티, subscript의 오버라이딩
을 금지할 수 있음

ex) final var, final func, final class func, final subscript
NHN	NEXT	Eunjoo	Im
Inheritance

Subclassing
(1)
출처: Apple Inc. The Swift Programming Language (Swift 3)
class Vehicle {

var currentSpeed = 0.0

var description: String {

return "traveling at (currentSpeed) miles per hour"

}

func makeNoise() {

// do nothing - an arbitrary vehicle doesn't necessarily
make a noise

}

}

let someVehicle = Vehicle()

print("Vehicle: (someVehicle.description)")

// Vehicle: traveling at 0.0 miles per hour
기본 Class(Superclass)
NHN	NEXT	Eunjoo	Im
Inheritance

Subclassing
(1)
출처: Apple Inc. The Swift Programming Language (Swift 3)
class Bicycle: Vehicle {

var hasBasket = false

}

let bicycle = Bicycle()

bicycle.hasBasket = true

bicycle.currentSpeed = 15.0

print("Bicycle: (bicycle.description)")

// Bicycle: traveling at 15.0 miles per hour
Subclass
▪ subclassing 문법
class SomeSubclass: SomeSuperclass {

}
superclass의 property 및
method를 자동으로 가짐

- currentSpeed

- desription

- makeNoise()
superclass에 없는 

새 프로퍼티를 설정
superclass에서

상속받은 프로퍼티 값을 수정
superclass의 프로퍼티를

subclass에서 호출할 수 있음
NHN	NEXT	Eunjoo	Im
Inheritance

Overriding
출처: Apple Inc. The Swift Programming Language (Swift 3)
class Train: Vehicle {

override func makeNoise() {

print("Choo Choo")

}

}

class Car: Vehicle {

var gear = 1

override var description: String {

return super.description + " in gear (gear)"

}

}

let car = Car()

car.currentSpeed = 25.0

car.gear = 3
superclass의 프로퍼티
currentSpeed를 오버라이딩
superclass의 메서드
makeNoise()를 오버라이딩
NHN	NEXT	Eunjoo	Im
Inheritance

Property

Observers
출처: Apple Inc. The Swift Programming Language (Swift 3)
class AutomaticCar: Car {

override var currentSpeed: Double {

didSet {

gear = Int(currentSpeed / 10.0) + 1

}

}

}

let automatic = AutomaticCar()

automatic.currentSpeed = 35.0

print("AutomaticCar: (automatic.description)")

// AutomaticCar: traveling at 35.0 miles per hour in gear 4
superclass의 프로퍼티
currentSpeed를 오버라이딩
didSet 옵저버가 값을 설정해줌
▪ 상속받은 property에 property overriding을 사용해서
property observer로 활용할 수 있음

▪ 상속받은 property의 값이 변경됐는지 파악할 수 있음
NHN	NEXT	Eunjoo	Im
Initialization

소개
▪ class, structure, enumeration을 사용하기 위해 인스턴스를 준비
하는 과정

▪ stored property의 초기값 설정을 포함

▪ 속성값이 항상 동일하다면 initializer 안에서 값을 설정하지 말
고 기본값을 줄 것

▪ initializer

▪ 특정 타입의 새 인스턴스를 만들기 위해 부르는 특별한 메서드

▪ Objective-C와 달리 값을 반환하지 않음

▪ deinitializer

▪ class의 delallocate 이전에 해야할 특정 작업을 정의
init() {

// 초기화 작업 수행

}
struct Fahrenheit {

var temperature: Double

init() {

temperature = 32.0

}

}
출처: Apple Inc. The Swift Programming Language (Swift 3)
NHN	NEXT	Eunjoo	Im
Initialization

커스터마이징
▪ 입력 매개변수와 옵셔널 프로퍼티 타입을 활용하거나,

상수 프로퍼티를 할당해서 initialzation 프로세스를

커스터마이징할 수 있음

▪ initializer를 정의하면서 initialization 매개변수를 제공할
수 있음
0
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) 

let freezingPointOfWater = Celsius(fromKelvin: 273.15)
boilingPointOfWater.temp
eratureInCelsius is 100.0
freezingPointOfWater.temp
eratureInCelsius is 0.0
출처: Apple Inc. The Swift Programming Language (Swift 3)
NHN	NEXT	Eunjoo	Im
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)

let veryGreen = Color(0.0, 1.0, 0.0)
Initialization

매개변수와
인자 이름(1)
▪ initializer는 식별 가능한 이름이 없으므로, 이름을 지정하
지 않으면 자동으로 모든 매개변수에 인자 이름을 부여함
어떻게	될까요?
{
출처: Apple Inc. The Swift Programming Language (Swift 3)
NHN	NEXT	Eunjoo	Im
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)

let veryGreen = Color(0.0, 1.0, 0.0)
Initialization

매개변수와
인자 이름(2)
실행됨	
실행됨	
compile-time	error	
-	argument	labels	are	required
출처: Apple Inc. The Swift Programming Language (Swift 3)
NHN	NEXT	Eunjoo	Im
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

매개변수와
인자 이름(3)
▪ 매개변수 이름 없이 initializer 정의하기

출처: Apple Inc. The Swift Programming Language (Swift 3)
인자 이름이 없어도

지정하는 것이 명확하며

_ 로 이름이 없음을 명시해줌
어떻게	하면	아래처럼	초기화할	수	있을까요?
???
NHN	NEXT	Eunjoo	Im
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

매개변수와
인자 이름(3)
▪ initializer는 식별 가능한 이름이 없으므로, 이름을 지정하
지 않으면 자동으로 모든 매개변수에 인자 이름을 부여함
출처: Apple Inc. The Swift Programming Language (Swift 3)
인자 이름이 없어도

지정하는 것이 명확하며

_ 로 이름이 없음을 명시해줌
NHN	NEXT	Eunjoo	Im
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()

cheeseQuestion.response = "Yes, I do like cheese."
Initialization

Optional

Property
▪ stored property가 값이 없으면 nil로 초기화되며
optional 타입으로 지정됨
출처: Apple Inc. The Swift Programming Language (Swift 3)
여기서 값을 지정하기 전까지
response의 값은 nil
response의 타입은

옵셔널 스트링(String?)으로

아직 스트링 값이 없다는 뜻
NHN	NEXT	Eunjoo	Im
class SurveyQuestion {

let text: String

var response: String?

init(text: String) {

self.text = text

}

func ask() {

print(text)

}

}
Initialization

Constant

Property(1)
▪ constant property(let)이라도 초기화 과정 중에는 값을
바꿀 수 있음

▪ 한 번 값을 지정한 constant property는 값을 바꿀 수 없음

▪ constant property는 subclass에서 값을 바꿀 수 없음
출처: Apple Inc. The Swift Programming Language (Swift 3)
let beetsQuestion = SurveyQuestion(text: "How about
beets?")

beetsQuestion.ask()

beetsQuestion.response = "I also like beets. (But not with
cheese.)"
// Prints "How about beets?"어떻게	될까요?
NHN	NEXT	Eunjoo	Im
class SurveyQuestion {

let text: String

var response: String?

init(text: String) {

self.text = text

}

func ask() {

print(text)

}

}
Initialization

Constant

Property(1)
▪ constant property(let)이라도 초기화 과정 중에는 값을
바꿀 수 있음

▪ 한 번 값을 지정한 constant property는 값을 바꿀 수 없음

▪ constant property는 subclass에서 값을 바꿀 수 없음
출처: Apple Inc. The Swift Programming Language (Swift 3)
let beetsQuestion = SurveyQuestion(text: "How about
beets?")

beetsQuestion.ask()

beetsQuestion.response = "I also like beets. (But not with
cheese.)"
// Prints "How about beets?"
NHN	NEXT	Eunjoo	Im
Initialization

Default

Initializer
▪ 모든 프로퍼티의 기본값이 이미 지정됐다면 매개변수 없이
도 초기화가 가능
출처: Apple Inc. The Swift Programming Language (Swift 3)
class ShoppingListItem {

var name: String?

var quantity = 1

var purchased = false

}

var item = ShoppingListItem()
struct Size {

var width = 0.0, height = 0.0

}

let twoByTwo = Size(width: 2.0, height: 2.0)
▪ structure type의 경우 Initializer를 멤버화할 수 있음
자동으로 멤버를 반영한 초기화
메서드를 만들어줌:
init(width:height:)
NHN	NEXT	Eunjoo	Im
Initialization

initializer

deligation(1)
▪ initializing 중 다른 initializer를 부를 수 있음

▪ 여러 initializer에서 코드가 중복되는 것을 방지

▪ value type, class type에 따라 다른 동작

▪ value type: self.init

▪ 커스텀 initializer를 만든 경우 사용 불가능
(initializer deligation을 동시에 사용하기를 원하면
extension 사용)
출처: Apple Inc. The Swift Programming Language (Swift 3)
NHN	NEXT	Eunjoo	Im
Initialization

initializer

deligation(2)
출처: Apple Inc. The Swift Programming Language (Swift 3)
struct Size {

var width = 0.0, 

height = 0.0

}

struct Point {

var x = 0.0,

y = 0.0

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

}

}
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)
어떻게	될까요?
어떻게	될까요?
어떻게	될까요?
NHN	NEXT	Eunjoo	Im
Initialization

initializer

deligation(3)
출처: Apple Inc. The Swift Programming Language (Swift 3)
struct Size {

var width = 0.0, 

height = 0.0

}

struct Point {

var x = 0.0,

y = 0.0

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

}

}
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)
NHN	NEXT	Eunjoo	Im
Initialization

Class

Inheritance
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ class의 모든 stored property는 (상속받은 stored
property 포함) initializing 중에 초기값을 할당해야 함

▪ class의 initializer는 두 종류

▪ designated initializer (지정 이니셜라이저)

▪ convenience initializer (편의 이니셜라이저)

▪ Designated initializer

▪ class의 기본 initializer

▪ 모든 프로퍼티를 초기화함

▪ 최소 하나 이상의 Designated Initializer 설정 필수

▪ superclass의 initialzer로 연계됨

▪ Convenience initializer

▪ 보조적인 initialized (필수 x)

▪ Designated Initializer를 호출하도록 하거나,

특별한 사용예를 위해 인스턴스를 만들도록 할 수 있음
init(parameters)	{	
statements	
}
convenience	init(parameters)	{	
statements	
}
NHN	NEXT	Eunjoo	Im
Initialization

Inheritance

& Overriding
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ Objectice-C와 달리 superclass의 initializer를
subclass가 기본으로 상속받지 않음

▪ superclass와 동일한 initializer를 subclass에서 사용하
려면 구현 필요

▪ override 접두어 사용
class Bicycle: Vehicle {

override init() {

super.init()

numberOfWheels = 2

}

}
▪ 특정 조건 하에서는 superclass의 initializer를 상속받음

▪ subclass에 designated initializer가 없는 경우

▪ superclass의 designated initializer를 모두 구현한
경우
NHN	NEXT	Eunjoo	Im
Initialization

Failable

Initializer(1)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ initialization 매개변수 값이 유효하지 않거나, 필요한 외부
자원이 없는 등의 경우 Initialization이 실패할 수 있음

▪ 하나 이상의 Failable Initializer(실패할 수 있는 Initializer)
를 지정해서 이를 방지

▪ init? 키워드를 사용해 옵셔널 타입을 생성하며, 초기화 실패
시 nil을 반환함

▪ required 키워드를 사용해 subclass에서 필수 구현 지정
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)")

}

let anonymousCreature = Animal(species: "")

if anonymousCreature == nil {

print("The anonymous creature could not be initialized")

}
NHN	NEXT	Eunjoo	Im
Initialization

Failable

Initializer(2)
출처: Apple Inc. The Swift Programming Language (Swift 3)
enum TemperatureUnit {

case kelvin, celsius,
fahrenheit

init?(symbol: Character) {

switch symbol {

case "K":

self = .kelvin

case "C":

self = .celsius
enum TemperatureUnit: Character {

case kelvin = "K", celsius = “C”

}

let fahrenheitUnit = TemperatureUnit(rawValue: "F")

if fahrenheitUnit != nil {

print("This is a defined temperature unit, so initialization
succeeded.")
case "F":

self = .fahrenheit

default:

return nil

}

}

}

let fahrenheitUnit =
TemperatureUnit(symbol: "F")
▪ Enumeration의 Failable Initializer
NHN	NEXT	Eunjoo	Im
Initialization

Failable

Initializer(3)
출처: Apple Inc. The Swift Programming Language (Swift 3)
class Product {

let name: String

init?(name: String) {

if name.isEmpty { 

return nil

}

self.name = name

}

}
if let oneUnnamed = CartItem(name: "", quantity: 1) {

print("Item: (oneUnnamed.name), quantity: 
(oneUnnamed.quantity)")

} else {

print("Unable to initialize one unnamed product")

}

// Prints "Unable to initialize one unnamed product"
class CartItem: Product {

let quantity: Int

init?(name: String, quantity: Int) {

if quantity < 1 { 

return nil }

self.quantity = quantity

super.init(name: name)

}

}
▪ Failable Initializer 전파
NHN	NEXT	Eunjoo	Im
Initialization

Failable

Initializer(4)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ override: 키워드를 사용해 오버라이딩 가능
▪ init?: 옵셔널 인스턴스를 생성하는 failable initializer
enum Color : Int {

case Red = 0, Green = 1, Blue = 2

var rawValue: Int { /* returns raw value for current case */ }

init?(rawValue: Int) {

switch rawValue { 

case 0: self = .Red

//

}

}

}
class UntitledDocument: Document {

override init() {

super.init(name: "[Untitled]")!

}

}
NHN	NEXT	Eunjoo	Im
Initialization

프로퍼티

초기값 설정(1)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ closure나 전역 함수를 사용해 프로퍼티 기본값 설정 가능

▪ 초기화될 때마다 closure/함수가 불려 프로퍼티에 기본값
을 지정함
class SomeClass {

let someProperty: SomeType = {

// create a default value for someProperty inside this
closure

// someValue must be of the same type as SomeType

return someValue

}()
NHN	NEXT	Eunjoo	Im
Initialization

프로퍼티

초기값 설정(2)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ 체스판 생성 예제
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]

}

}
let board = Chessboard()

print(board.squareIsBlackAt(row: 0,
column: 1))

// Prints "true"

print(board.squareIsBlackAt(row: 7,
column: 7))

// Prints "false”
어떻게	될까요?
어떻게	될까요?
NHN	NEXT	Eunjoo	Im
Initialization

프로퍼티

초기값 설정(3)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ 체스판 생성 예제
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]

}

}
let board = Chessboard()

print(board.squareIsBlackAt(row: 0,
column: 1))

// Prints "true"

print(board.squareIsBlackAt(row: 7,
column: 7))

// Prints "false”
NHN	NEXT	Eunjoo	Im
참고

자료
https://itun.es/kr/jEUH0.l
Apple Inc. The Swift Programming Language (Swift 3)
NHN	NEXT	Eunjoo	Im
Thank	
You

More Related Content

What's hot (20)

PDF
9 swift 클로저1
Changwon National University
 
PDF
스위프트 성능 이해하기
Yongha Yoo
 
PPTX
0.javascript기본(~3일차내)
Sung-hoon Ma
 
PDF
스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)
Yongha Yoo
 
PPTX
Jupyter notebok tensorboard 실행하기_20160706
Yong Joon Moon
 
PDF
Javascript
Hong Hyo Sang
 
PDF
6 swift 고급함수
Changwon National University
 
PPTX
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Circulus
 
PDF
Do swift: Swift 무작정 해보기
YoonBong Steve Kim
 
PPTX
자바스크립트 기초문법~함수기초
진수 정
 
DOCX
Javascript 완벽 가이드 정리
ETRIBE_STG
 
PDF
일단 시작하는 코틀린
Park JoongSoo
 
PDF
Java 변수자료형
Hyosang Hong
 
PPTX
Startup JavaScript 4 - 객체
Circulus
 
PDF
Java 이해하기 쉬운 코드 20210405
Hyosang Hong
 
PDF
iOS 메모리관리
Changwon National University
 
PDF
1.Startup JavaScript - 프로그래밍 기초
Circulus
 
PPTX
프론트엔드스터디 E05 js closure oop
Young-Beom Rhee
 
PDF
Secrets of the JavaScript Ninja - Chapter 3. Functions are Fundamental
Hyuncheol Jeon
 
PDF
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
NAVER D2
 
9 swift 클로저1
Changwon National University
 
스위프트 성능 이해하기
Yongha Yoo
 
0.javascript기본(~3일차내)
Sung-hoon Ma
 
스위프트, 코틀린과 모던언어의 특징 (Swift, Kotlin and Modern Languages)
Yongha Yoo
 
Jupyter notebok tensorboard 실행하기_20160706
Yong Joon Moon
 
Javascript
Hong Hyo Sang
 
6 swift 고급함수
Changwon National University
 
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Circulus
 
Do swift: Swift 무작정 해보기
YoonBong Steve Kim
 
자바스크립트 기초문법~함수기초
진수 정
 
Javascript 완벽 가이드 정리
ETRIBE_STG
 
일단 시작하는 코틀린
Park JoongSoo
 
Java 변수자료형
Hyosang Hong
 
Startup JavaScript 4 - 객체
Circulus
 
Java 이해하기 쉬운 코드 20210405
Hyosang Hong
 
iOS 메모리관리
Changwon National University
 
1.Startup JavaScript - 프로그래밍 기초
Circulus
 
프론트엔드스터디 E05 js closure oop
Young-Beom Rhee
 
Secrets of the JavaScript Ninja - Chapter 3. Functions are Fundamental
Hyuncheol Jeon
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
NAVER D2
 

Similar to Swift3 subscript inheritance initialization (20)

PDF
[1B1]스위프트프로그래밍언어
NAVER D2
 
PDF
[Osxdev]4.swift
NAVER D2
 
PPTX
Swift 0x0e 초기화
Hyun Jin Moon
 
PPTX
Swift3 : class and struct(+property+method)
승욱 정
 
PDF
[Swift] Extensions
Bill Kim
 
PDF
[SwiftStudy 2016] 2장. Swift 타입 파트 1
Keunhyun Oh
 
PPTX
Swift2
HyungKuIm
 
PDF
[Swift] Subscripts
Bill Kim
 
PPTX
Inheritance
JIhyun Choi
 
PDF
[Swift] Properties
Bill Kim
 
PDF
Hello Swift 2/5 - Basic2
Cody Yun
 
PDF
Swift 3 Programming for iOS : class and structure
Kwang Woo NAM
 
PDF
10 swift 열거형구조체클래스
Changwon National University
 
PDF
[Swift] Protocol (1/2)
Bill Kim
 
PDF
Swift5 vs objective c
Bill Kim
 
PPT
iOS 앱 개발 강의 자료 #1
Jeong-Hoon Mo
 
PPTX
15 swift 클래스
Changwon National University
 
PDF
2 swift 상수_변수_튜플
Changwon National University
 
PPT
Swift basic operators-controlflow
wileychoi
 
PPTX
Swift 0x0d 상속
Hyun Jin Moon
 
[1B1]스위프트프로그래밍언어
NAVER D2
 
[Osxdev]4.swift
NAVER D2
 
Swift 0x0e 초기화
Hyun Jin Moon
 
Swift3 : class and struct(+property+method)
승욱 정
 
[Swift] Extensions
Bill Kim
 
[SwiftStudy 2016] 2장. Swift 타입 파트 1
Keunhyun Oh
 
Swift2
HyungKuIm
 
[Swift] Subscripts
Bill Kim
 
Inheritance
JIhyun Choi
 
[Swift] Properties
Bill Kim
 
Hello Swift 2/5 - Basic2
Cody Yun
 
Swift 3 Programming for iOS : class and structure
Kwang Woo NAM
 
10 swift 열거형구조체클래스
Changwon National University
 
[Swift] Protocol (1/2)
Bill Kim
 
Swift5 vs objective c
Bill Kim
 
iOS 앱 개발 강의 자료 #1
Jeong-Hoon Mo
 
15 swift 클래스
Changwon National University
 
2 swift 상수_변수_튜플
Changwon National University
 
Swift basic operators-controlflow
wileychoi
 
Swift 0x0d 상속
Hyun Jin Moon
 
Ad

Swift3 subscript inheritance initialization

  • 2. NHN NEXT Eunjoo Im Subscript 소개 ▪ Class, Structure, Enumeration의 subscript라는 메서 드로 정의해서 collection 등의 멤버에 쉽게 접근할 수 있음 ▪ index를 통해 쉽게 값을 저장하거나 읽을 수 있음 
 ex) someArray[index], someDicitonary[key] ▪ 한 대상에 대해 다수의 subscript를 만들 수 있음 ▪ 예약어이므로 func를 쓸 필요 없음 출처: Apple Inc. The Swift Programming Language (Swift 3) subscript(index: Int) -> Int { get { // 원하는 subscript 값을 return } set(newValue) { // 원하는 subscript 값을 설정 } }
  • 3. NHN NEXT Eunjoo Im Subscript 기본 문법(1) ▪ 기본 매개변수 newValue: 생략 가능, 새 이름 설정 가능 ▪ 매개 변수는 여러 개도 설정 가능 ▪ read-only 프로퍼티에 대해서는 get 키워드 생략 가능 subscript(index: Int) -> Int { } struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print("(threeTimesTable[6])") // "18" 출처: Apple Inc. The Swift Programming Language (Swift 3) 어떤 값이 찍힐까요?
  • 4. NHN NEXT Eunjoo Im Subscript 기본 문법(2) ▪ 기본 매개변수 newValue: 생략 가능, 새 이름 설정 가능 ▪ 매개 변수는 여러 개도 설정 가능 ▪ read-only 프로퍼티에 대해서는 get 키워드 생략 가능 subscript(index: Int) -> Int { } struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print("(threeTimesTable[6])") // "18" 출처: Apple Inc. The Swift Programming Language (Swift 3)
  • 5. NHN NEXT Eunjoo Im Subscript 사용예 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ collection, list, sequence의 멤버에 쉽게 엑세스하는 방 법으로 사용 ▪ Dictionary에 subscript를 설정해서 인스턴스에 저장된 값을 가져올 수 있음 ▪ Dictionary의 키 타입에 맞는 키를 사용해서 값을 설정할 수 있음 ▪ 상위 예제의 다리 숫자는 Int?로 Optional Int임 ▪ 모든 Key가 Value를 가지지 않아도 됨 ▪ Value를 삭제하려면 nil로 설정 var numberOfLeg = ["spider": 8, "ant": 6, "cat": 4] numberOfLeg[“bird"] = 2
  • 6. NHN NEXT Eunjoo Im Subscript 옵션(1) 출처: Apple Inc. The Swift Programming Language (Swift 3) 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 } } } matrix[0, 1] = 1.5 matrix[1, 0] = 3.2 var matrix = Matrix(rows: 2, columns: 2) 어떤 행렬이 될까요?
  • 7. NHN NEXT Eunjoo Im Subscript 옵션(2) 출처: Apple Inc. The Swift Programming Language (Swift 3) 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 } } } matrix[0, 1] = 1.5 matrix[1, 0] = 3.2 var matrix = Matrix(rows: 2, columns: 2)
  • 8. NHN NEXT Eunjoo Im Inheritance 소개 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ Class는 메서드, 프로퍼티 등을 다른 Class로부터 상속받을 수 있음 ▪ 상속한 Class는 superclass, 상속받은 Class는 subclass ▪ Class를 다른 타입과 구분짓는 특징 ▪ 상속받은 메서드, 프로퍼티, subscript를 호출하거나, overriding해서 사용할 수 있음 ▪ 상속받은 프로퍼티에 property observer를 추가해서 프로 퍼티가 수정된 것을 파악할 수 있음
 (단, Stored나 computed 프로퍼티로 정의돼야 함) ▪ subclass를 다시 subclassing할 수도 있음 ▪ final을 사용해서 메서드, 프로퍼티, subscript의 오버라이딩 을 금지할 수 있음
 ex) final var, final func, final class func, final subscript
  • 9. NHN NEXT Eunjoo Im Inheritance Subclassing (1) 출처: Apple Inc. The Swift Programming Language (Swift 3) class Vehicle { var currentSpeed = 0.0 var description: String { return "traveling at (currentSpeed) miles per hour" } func makeNoise() { // do nothing - an arbitrary vehicle doesn't necessarily make a noise } } let someVehicle = Vehicle() print("Vehicle: (someVehicle.description)") // Vehicle: traveling at 0.0 miles per hour 기본 Class(Superclass)
  • 10. NHN NEXT Eunjoo Im Inheritance Subclassing (1) 출처: Apple Inc. The Swift Programming Language (Swift 3) class Bicycle: Vehicle { var hasBasket = false } let bicycle = Bicycle() bicycle.hasBasket = true bicycle.currentSpeed = 15.0 print("Bicycle: (bicycle.description)") // Bicycle: traveling at 15.0 miles per hour Subclass ▪ subclassing 문법 class SomeSubclass: SomeSuperclass { } superclass의 property 및 method를 자동으로 가짐 - currentSpeed - desription - makeNoise() superclass에 없는 
 새 프로퍼티를 설정 superclass에서
 상속받은 프로퍼티 값을 수정 superclass의 프로퍼티를
 subclass에서 호출할 수 있음
  • 11. NHN NEXT Eunjoo Im Inheritance Overriding 출처: Apple Inc. The Swift Programming Language (Swift 3) class Train: Vehicle { override func makeNoise() { print("Choo Choo") } } class Car: Vehicle { var gear = 1 override var description: String { return super.description + " in gear (gear)" } } let car = Car() car.currentSpeed = 25.0 car.gear = 3 superclass의 프로퍼티 currentSpeed를 오버라이딩 superclass의 메서드 makeNoise()를 오버라이딩
  • 12. NHN NEXT Eunjoo Im Inheritance Property Observers 출처: Apple Inc. The Swift Programming Language (Swift 3) class AutomaticCar: Car { override var currentSpeed: Double { didSet { gear = Int(currentSpeed / 10.0) + 1 } } } let automatic = AutomaticCar() automatic.currentSpeed = 35.0 print("AutomaticCar: (automatic.description)") // AutomaticCar: traveling at 35.0 miles per hour in gear 4 superclass의 프로퍼티 currentSpeed를 오버라이딩 didSet 옵저버가 값을 설정해줌 ▪ 상속받은 property에 property overriding을 사용해서 property observer로 활용할 수 있음 ▪ 상속받은 property의 값이 변경됐는지 파악할 수 있음
  • 13. NHN NEXT Eunjoo Im Initialization 소개 ▪ class, structure, enumeration을 사용하기 위해 인스턴스를 준비 하는 과정 ▪ stored property의 초기값 설정을 포함 ▪ 속성값이 항상 동일하다면 initializer 안에서 값을 설정하지 말 고 기본값을 줄 것 ▪ initializer ▪ 특정 타입의 새 인스턴스를 만들기 위해 부르는 특별한 메서드 ▪ Objective-C와 달리 값을 반환하지 않음 ▪ deinitializer ▪ class의 delallocate 이전에 해야할 특정 작업을 정의 init() { // 초기화 작업 수행 } struct Fahrenheit { var temperature: Double init() { temperature = 32.0 } } 출처: Apple Inc. The Swift Programming Language (Swift 3)
  • 14. NHN NEXT Eunjoo Im Initialization 커스터마이징 ▪ 입력 매개변수와 옵셔널 프로퍼티 타입을 활용하거나,
 상수 프로퍼티를 할당해서 initialzation 프로세스를
 커스터마이징할 수 있음 ▪ initializer를 정의하면서 initialization 매개변수를 제공할 수 있음 0 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) let freezingPointOfWater = Celsius(fromKelvin: 273.15) boilingPointOfWater.temp eratureInCelsius is 100.0 freezingPointOfWater.temp eratureInCelsius is 0.0 출처: Apple Inc. The Swift Programming Language (Swift 3)
  • 15. NHN NEXT Eunjoo Im 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) let veryGreen = Color(0.0, 1.0, 0.0) Initialization 매개변수와 인자 이름(1) ▪ initializer는 식별 가능한 이름이 없으므로, 이름을 지정하 지 않으면 자동으로 모든 매개변수에 인자 이름을 부여함 어떻게 될까요? { 출처: Apple Inc. The Swift Programming Language (Swift 3)
  • 16. NHN NEXT Eunjoo Im 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) let veryGreen = Color(0.0, 1.0, 0.0) Initialization 매개변수와 인자 이름(2) 실행됨 실행됨 compile-time error - argument labels are required 출처: Apple Inc. The Swift Programming Language (Swift 3)
  • 17. NHN NEXT Eunjoo Im 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 매개변수와 인자 이름(3) ▪ 매개변수 이름 없이 initializer 정의하기 출처: Apple Inc. The Swift Programming Language (Swift 3) 인자 이름이 없어도
 지정하는 것이 명확하며
 _ 로 이름이 없음을 명시해줌 어떻게 하면 아래처럼 초기화할 수 있을까요? ???
  • 18. NHN NEXT Eunjoo Im 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 매개변수와 인자 이름(3) ▪ initializer는 식별 가능한 이름이 없으므로, 이름을 지정하 지 않으면 자동으로 모든 매개변수에 인자 이름을 부여함 출처: Apple Inc. The Swift Programming Language (Swift 3) 인자 이름이 없어도
 지정하는 것이 명확하며
 _ 로 이름이 없음을 명시해줌
  • 19. NHN NEXT Eunjoo Im 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() cheeseQuestion.response = "Yes, I do like cheese." Initialization Optional Property ▪ stored property가 값이 없으면 nil로 초기화되며 optional 타입으로 지정됨 출처: Apple Inc. The Swift Programming Language (Swift 3) 여기서 값을 지정하기 전까지 response의 값은 nil response의 타입은
 옵셔널 스트링(String?)으로
 아직 스트링 값이 없다는 뜻
  • 20. NHN NEXT Eunjoo Im class SurveyQuestion { let text: String var response: String? init(text: String) { self.text = text } func ask() { print(text) } } Initialization Constant Property(1) ▪ constant property(let)이라도 초기화 과정 중에는 값을 바꿀 수 있음 ▪ 한 번 값을 지정한 constant property는 값을 바꿀 수 없음 ▪ constant property는 subclass에서 값을 바꿀 수 없음 출처: Apple Inc. The Swift Programming Language (Swift 3) let beetsQuestion = SurveyQuestion(text: "How about beets?") beetsQuestion.ask() beetsQuestion.response = "I also like beets. (But not with cheese.)" // Prints "How about beets?"어떻게 될까요?
  • 21. NHN NEXT Eunjoo Im class SurveyQuestion { let text: String var response: String? init(text: String) { self.text = text } func ask() { print(text) } } Initialization Constant Property(1) ▪ constant property(let)이라도 초기화 과정 중에는 값을 바꿀 수 있음 ▪ 한 번 값을 지정한 constant property는 값을 바꿀 수 없음 ▪ constant property는 subclass에서 값을 바꿀 수 없음 출처: Apple Inc. The Swift Programming Language (Swift 3) let beetsQuestion = SurveyQuestion(text: "How about beets?") beetsQuestion.ask() beetsQuestion.response = "I also like beets. (But not with cheese.)" // Prints "How about beets?"
  • 22. NHN NEXT Eunjoo Im Initialization Default Initializer ▪ 모든 프로퍼티의 기본값이 이미 지정됐다면 매개변수 없이 도 초기화가 가능 출처: Apple Inc. The Swift Programming Language (Swift 3) class ShoppingListItem { var name: String? var quantity = 1 var purchased = false } var item = ShoppingListItem() struct Size { var width = 0.0, height = 0.0 } let twoByTwo = Size(width: 2.0, height: 2.0) ▪ structure type의 경우 Initializer를 멤버화할 수 있음 자동으로 멤버를 반영한 초기화 메서드를 만들어줌: init(width:height:)
  • 23. NHN NEXT Eunjoo Im Initialization initializer deligation(1) ▪ initializing 중 다른 initializer를 부를 수 있음 ▪ 여러 initializer에서 코드가 중복되는 것을 방지 ▪ value type, class type에 따라 다른 동작 ▪ value type: self.init ▪ 커스텀 initializer를 만든 경우 사용 불가능 (initializer deligation을 동시에 사용하기를 원하면 extension 사용) 출처: Apple Inc. The Swift Programming Language (Swift 3)
  • 24. NHN NEXT Eunjoo Im Initialization initializer deligation(2) 출처: Apple Inc. The Swift Programming Language (Swift 3) struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } 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) } } 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) 어떻게 될까요? 어떻게 될까요? 어떻게 될까요?
  • 25. NHN NEXT Eunjoo Im Initialization initializer deligation(3) 출처: Apple Inc. The Swift Programming Language (Swift 3) struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } 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) } } 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)
  • 26. NHN NEXT Eunjoo Im Initialization Class Inheritance 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ class의 모든 stored property는 (상속받은 stored property 포함) initializing 중에 초기값을 할당해야 함 ▪ class의 initializer는 두 종류 ▪ designated initializer (지정 이니셜라이저) ▪ convenience initializer (편의 이니셜라이저) ▪ Designated initializer ▪ class의 기본 initializer ▪ 모든 프로퍼티를 초기화함 ▪ 최소 하나 이상의 Designated Initializer 설정 필수 ▪ superclass의 initialzer로 연계됨 ▪ Convenience initializer ▪ 보조적인 initialized (필수 x) ▪ Designated Initializer를 호출하도록 하거나,
 특별한 사용예를 위해 인스턴스를 만들도록 할 수 있음 init(parameters) { statements } convenience init(parameters) { statements }
  • 27. NHN NEXT Eunjoo Im Initialization Inheritance & Overriding 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ Objectice-C와 달리 superclass의 initializer를 subclass가 기본으로 상속받지 않음 ▪ superclass와 동일한 initializer를 subclass에서 사용하 려면 구현 필요 ▪ override 접두어 사용 class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } ▪ 특정 조건 하에서는 superclass의 initializer를 상속받음 ▪ subclass에 designated initializer가 없는 경우 ▪ superclass의 designated initializer를 모두 구현한 경우
  • 28. NHN NEXT Eunjoo Im Initialization Failable Initializer(1) 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ initialization 매개변수 값이 유효하지 않거나, 필요한 외부 자원이 없는 등의 경우 Initialization이 실패할 수 있음 ▪ 하나 이상의 Failable Initializer(실패할 수 있는 Initializer) 를 지정해서 이를 방지 ▪ init? 키워드를 사용해 옵셔널 타입을 생성하며, 초기화 실패 시 nil을 반환함 ▪ required 키워드를 사용해 subclass에서 필수 구현 지정 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)") } let anonymousCreature = Animal(species: "") if anonymousCreature == nil { print("The anonymous creature could not be initialized") }
  • 29. NHN NEXT Eunjoo Im Initialization Failable Initializer(2) 출처: Apple Inc. The Swift Programming Language (Swift 3) enum TemperatureUnit { case kelvin, celsius, fahrenheit init?(symbol: Character) { switch symbol { case "K": self = .kelvin case "C": self = .celsius enum TemperatureUnit: Character { case kelvin = "K", celsius = “C” } let fahrenheitUnit = TemperatureUnit(rawValue: "F") if fahrenheitUnit != nil { print("This is a defined temperature unit, so initialization succeeded.") case "F": self = .fahrenheit default: return nil } } } let fahrenheitUnit = TemperatureUnit(symbol: "F") ▪ Enumeration의 Failable Initializer
  • 30. NHN NEXT Eunjoo Im Initialization Failable Initializer(3) 출처: Apple Inc. The Swift Programming Language (Swift 3) class Product { let name: String init?(name: String) { if name.isEmpty { return nil } self.name = name } } if let oneUnnamed = CartItem(name: "", quantity: 1) { print("Item: (oneUnnamed.name), quantity: (oneUnnamed.quantity)") } else { print("Unable to initialize one unnamed product") } // Prints "Unable to initialize one unnamed product" class CartItem: Product { let quantity: Int init?(name: String, quantity: Int) { if quantity < 1 { return nil } self.quantity = quantity super.init(name: name) } } ▪ Failable Initializer 전파
  • 31. NHN NEXT Eunjoo Im Initialization Failable Initializer(4) 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ override: 키워드를 사용해 오버라이딩 가능 ▪ init?: 옵셔널 인스턴스를 생성하는 failable initializer enum Color : Int { case Red = 0, Green = 1, Blue = 2 var rawValue: Int { /* returns raw value for current case */ } init?(rawValue: Int) { switch rawValue { case 0: self = .Red // } } } class UntitledDocument: Document { override init() { super.init(name: "[Untitled]")! } }
  • 32. NHN NEXT Eunjoo Im Initialization 프로퍼티 초기값 설정(1) 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ closure나 전역 함수를 사용해 프로퍼티 기본값 설정 가능 ▪ 초기화될 때마다 closure/함수가 불려 프로퍼티에 기본값 을 지정함 class SomeClass { let someProperty: SomeType = { // create a default value for someProperty inside this closure // someValue must be of the same type as SomeType return someValue }()
  • 33. NHN NEXT Eunjoo Im Initialization 프로퍼티 초기값 설정(2) 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ 체스판 생성 예제 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] } } let board = Chessboard() print(board.squareIsBlackAt(row: 0, column: 1)) // Prints "true" print(board.squareIsBlackAt(row: 7, column: 7)) // Prints "false” 어떻게 될까요? 어떻게 될까요?
  • 34. NHN NEXT Eunjoo Im Initialization 프로퍼티 초기값 설정(3) 출처: Apple Inc. The Swift Programming Language (Swift 3) ▪ 체스판 생성 예제 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] } } let board = Chessboard() print(board.squareIsBlackAt(row: 0, column: 1)) // Prints "true" print(board.squareIsBlackAt(row: 7, column: 7)) // Prints "false”