반응형

프로토콜과 익스텐션을 다룹니다.



A Swift Tour ( https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html  ) 문서의 코드를 Swift Playground( https://swiftfiddle.com/  ) 에서 실행시켜 보며 진행해보았습니다. 

 

본 문서는 공부한 내용을 정리하는 목적으로 작성되었으며 A Swift Tour 문서의 내용을 바탕으로 하고 있습니다. 잘못된 점이 있을 수 있습니다



2021. 10. 28   최초작성

2021. 11. 02   접속 불가 상태인 Swift Playground 사이트 변경

2022. 10. 22   최종수정

 

protocol 키워드를 사용하여 프로토콜을 정의합니다. 실제 구현을 하지는 않고 필요한 속성과 메서드를 정의만 합니다. 

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

 

클래스, 열거형, 구조체에서 프로토콜에 정의된 속성과 메서드를 구현합니다. 

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}


// 클래스 이름 다음에 콜론을 추가한 후, 구현할 프로토콜 이름을 적습니다. 

// 이후 프로토콜에 정의된 속성과 메서드를 구현합니다
struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"

    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}

 

구조체 SimpleStructure 선언에서 adjust 메소드 앞에  mutating 키워드의 사용하는 것은 구조체 내의 변수를 수정하는 메소드를 표시하기 위해서 입니다. 

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"

    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}

var b = SimpleStructure()

b.adjust()

print(b.simpleDescription)

 

실행결과입니다. 

 

클래스의 메서드는 항상 클래스내 변수를 수정할 수 있기 때문에 mutating를 사용하여 메소드에 표시할 필요가 없습니다. 

SimpleClass의 메소드에는 mutating가 없습니다. 

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."

    func adjust() {
        simpleDescription += "  Now 100% adjusted."
    }
}

var a = SimpleClass()

a.adjust()

print(a.simpleDescription)

 

실행결과입니다. 

 

extension 키워드를 사용하여 다른 곳에서 선언된 타입이나 라이브러리나 프레임워크에서 가져온 타입에서  프로토콜을 구현 하도록 할 수 있습니다. 

 

다음 예제 코드는 정수형 타입에 ExampleProtocol 프로토콜을 구현한 예제코드입니다. 

 

Int 타입의 메서드로 simpleDescription와 adjust를 구현합니다

 

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}

print(7.simpleDescription)



실행결과입니다.

 



정수 타입에서 adjust 메소드를 사용하려고 하면 다음과 같은 에러가 발생합니다.

https://swiftfiddle.com/ 에서 확인한 결과입니다. 

 

error: cannot use mutating member on immutable value: literals are not mutable

10.adjust()

~~ ^




Swift 강좌 1 - Hello, world

https://webnautes.tistory.com/1549



Swift 강좌 2 - 상수와 변수

https://webnautes.tistory.com/1550



Swift 강좌 3 - 제어문 : if, for - in, switch, repeat - while

https://webnautes.tistory.com/1551



Swift 강좌 4 - 함수

https://webnautes.tistory.com/1552



Swift 강좌 5 - 객체(Objects)와 클래스(Classes)

https://webnautes.tistory.com/1558



Swift 강좌 6 - 열거형(Enumerations)과 구조체(Structures)

https://webnautes.tistory.com/1559



Swift 강좌 7 - 프로토콜(Protocols)과 익스텐션(Extensions)

https://webnautes.tistory.com/1562



Swift 강좌 8 - 에러 처리(Error Handling)

https://webnautes.tistory.com/1566



Swift 강좌 9 - 제네릭(Generics)

https://webnautes.tistory.com/1568



문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts