36
NHN NEXT Eunjoo Im Swift3 Subscript Inheritance Initialization NHN NEXT Swift3 Sutdy

Swift3 subscript inheritance initialization

Embed Size (px)

Citation preview

Page 1: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

Swift3SubscriptInheritanceInitialization

NHN NEXT

Swift3 Sutdy

Page 2: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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 값을 설정

}

}

Page 3: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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)

어떤값이찍힐까요?

Page 4: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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)

Page 5: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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

Page 6: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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)

어떤행렬이될까요?

Page 7: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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)

Page 8: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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

Page 9: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InheritanceSubclassing

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

Page 10: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InheritanceSubclassing

(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에서 호출할 수 있음

Page 11: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InheritanceOverriding

출처: 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()를 오버라이딩

Page 12: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InheritanceProperty

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의 값이 변경됐는지 파악할 수 있음

Page 13: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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)

Page 14: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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.temperatureInCelsius is 100.0

freezingPointOfWater.temperatureInCelsius is 0.0

출처: Apple Inc. The Swift Programming Language (Swift 3)

Page 15: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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)

Page 16: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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-timeerror-argumentlabelsarerequired

출처: Apple Inc. The Swift Programming Language (Swift 3)

Page 17: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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)

인자 이름이 없어도 지정하는 것이 명확하며_ 로 이름이 없음을 명시해줌

어떻게하면아래처럼초기화할수있을까요?

???

Page 18: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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)

인자 이름이 없어도 지정하는 것이 명확하며_ 로 이름이 없음을 명시해줌

Page 19: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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

InitializationOptionalProperty

▪ stored property가 값이 없으면 nil로 초기화되며 optional 타입으로 지정됨

출처: Apple Inc. The Swift Programming Language (Swift 3)

여기서 값을 지정하기 전까지 response의 값은 nil

response의 타입은옵셔널 스트링(String?)으로아직 스트링 값이 없다는 뜻

Page 20: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

class SurveyQuestion {

let text: String

var response: String?

init(text: String) {

self.text = text

}

func ask() {

print(text)

}

}

InitializationConstant

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?"어떻게될까요?

Page 21: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

class SurveyQuestion {

let text: String

var response: String?

init(text: String) {

self.text = text

}

func ask() {

print(text)

}

}

InitializationConstant

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

Page 22: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InitializationDefault

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

Page 23: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

Initializationinitializer

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)

Page 24: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

Initializationinitializer

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)

어떻게될까요?

어떻게될까요?

어떻게될까요?

Page 25: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

Initializationinitializer

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)

Page 26: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InitializationClass

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

}

convenienceinit(parameters){statements

}

Page 27: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InitializationInheritance

& 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를 모두 구현한 경우

Page 28: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InitializationFailable

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

}

Page 29: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InitializationFailable

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

Page 30: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InitializationFailable

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 전파

Page 31: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

InitializationFailable

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

}

}

Page 32: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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

}()

Page 33: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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”

어떻게될까요?

어떻게될까요?

Page 34: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

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”

Page 35: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

참고자료

https://itun.es/kr/jEUH0.l

Apple Inc. The Swift Programming Language (Swift 3)

Page 36: Swift3 subscript inheritance initialization

NHNNEXTEunjooIm

ThankYou