아리의 iOS 탐구생활

[Swift] Protocol 3) 메소드의 대한 요구사항 본문

Swift/문법

[Swift] Protocol 3) 메소드의 대한 요구사항

Ari Lee 2021. 8. 18. 18:03
반응형
Method Requirements

👉🏻  프로토콜에서의 메소드 정의하기

protocol Protocols {
    func A(param: Int) -> Int
    static func B(param: String) -> String
    mutating func C(param: Double) -> Double // 값타입 전용은 아니다. 참조타입에서도 채택가능하다.
}

 

프로토콜은 메서드 이름, 파라미터 이름과 타입, 리턴 타입만 정의한다.

채택하여 메서드를 구현할때 구현부는 자유롭게 작성할 수 있다.

protocol Talk {
    func say()
}

class A: Talk {
    func say() {
        print("난 클래스 A라고 해.")
    }
}

 

 

 

 

만약 구조체안에 메서드가 프로퍼티의 값을 바꾸려한다면 mutating 키워드를 붙여줘야 한다.

그럼 프로토콜도 마찬가지로 mutating 키워드를 추가해줘야 한다.

이때 클래스는 참조타입이기 때문에 mutating 키워드를 메서드 앞에 붙여주지 않아도 프로토콜 요구사항을 충족시키기 때문에 에러가 발생하지 않는다.

👉🏻  예제 1

protocol renamed {
    mutating func newName()
}

struct A: renamed {
    var name: String = "Ari"
    mutating func newName() {
        name = "three"
    }
}

class B: renamed {
    var name: String = "Ari"
    func newName() {
        name = "three"
    }
}

 

 

 

 

👉🏻  예제 2

오버로딩 규칙에 따라서 이름이 동일한 메서드를
인스턴스 메서드와 타입 메서드로 동시에 구현할 수도 있다.
protocol Test {
    static func test()
}

class C: Test {
    var number = 0
    func test() {
        number = 10
    }
    
//    static func test() {
//        // 이 메서드는 서브클래스에 상속은 가능하지만 오버라이딩은 불가능하다.
//    }
    
    class func test() {
        // 이 메서드는 프로토콜을 충족하면서 상속과 오버라이딩도 가능하다.
    }
}

 

 

 

 

✔️  Reference

 

Protocols — The Swift Programming Language (Swift 5.5)

Protocols A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of tho

docs.swift.org

 

반응형
Comments