Apple-CS-interview / iOS-CS-interview

7 stars 0 forks source link

프로토콜이란 무엇인지 설명하시오. #17

Open Do-hyun-Kim opened 12 months ago

Do-hyun-Kim commented 11 months ago

프로토콜이란 무엇인지 설명하시오.

Protocol 이란

Property Requirements 정의

protocol SomeProtocol {

  // instance properties
  var mustBeSettable: Int { get set }
    var doesNotNeedToBeSettable: Int { get }

  // type property
  static var someTypeProperty: Int { get set }
}

Method Requirements 정의

protocol SomeProtocol {
    // Type Method 
    static func someTypeMethod()
}

protocol RandomNumberGenerator {
    // instance Method
    func random() -> Double
}

protocol Togglable {
    mutating func toggle()
} 

Initializer Requirements 정의

protocol SomeProtocol {
    init(someParameter: Int)
}

class SomeClass: SomeProtocol {
    required init(someParameter: Int) {
        // initializer implementation goes here
    }
}

Protocol Composition 정의

protocol Named {
    var name: String { get }
}
protocol Aged {
    var age: Int { get }
}
struct Person: Named, Aged {
    var name: String
    var age: Int
}
func wishHappyBirthday(to celebrator: Named & Aged) {
    print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(to: birthdayPerson)

class Location {
    var latitude: Double
    var longitude: Double
    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }
}
class City: Location, Named {
    var name: String
    init(name: String, latitude: Double, longitude: Double) {
        self.name = name
        super.init(latitude: latitude, longitude: longitude)
    }
}

// Location : Super Class
// Named : Protocol
func beginConcert(in location: Location & Named) {
    print("Hello, \(location.name)!")
}

let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3)
beginConcert(in: seattle)

Protocol 다양한 활용

📝 참고 사이트

vichye-1 commented 11 months ago

프로토콜이란?

프로토콜 채택 방법

protocol Algorithm {
    var bfs: String { get set }
    var dp: String { get set }
    var math: String { get set }

    func test()
}

class company: Algorithm {
    var bfs: String = "Gold"
    var dp: String = "Sliver"
    var math: String = "Bronze"

    func test() {
        print("테스트 통과!")
    }
}

프로토콜의 일부 프로퍼티를 optional로 설정하고 싶을 때

@objc protocol Algorithm: AnyObject {
    var dp: String  { get set }
    @objc optional var bfs: String { get set }
}

class company: Algorithm {
    var dp: String = "Gold"
    var bfs: String = "Silver"

    func test() {
        print("테스트 통과!")
    }
}

let aCompany: Algorithm = company.init()
aCompany.dp    // Gold
aCompany.bfs   // Sliver

참고

Hminchae commented 11 months ago

프로토콜(Protocol)

프로토콜 정의

protocol 프로토콜 이름 {
프로토콜 정의
}

구조체, 클래스, 열거형 등에서 프로토콜을 채택하려면 타입 이름 뒤에 콜론(:)을 붙여준 후 채택할 프로토콜 이름을 쉼표(,)로 구분하여 명시함

struct SomeStruct: AProtocol, AnotherProtocol {
    // 구조체 정의
}

class SomeClass: AProtocol, AnotherProtocol {
    // 클래스 정의
}

enum SomeEnum: AProtocol, AnotherProtocol {
    // 열거형 정의
}

만약, 클래스가 다른 클래스를 상속받는다면 상속받을 클래스 이름 다음에 채택할 프로토콜을 나열

class SomeClass: SuperClass, AProtocol, AnotherProtocol {
    // 클래스 정의
}

프로토콜 요구사항

프로퍼티 요구

protocol AProtocol{
    var a: String{ get set }
    // AProtocol에 정의된 a는 읽기와 쓰기 모두를 요구했고
    var b: String{ get }
    // b는 읽기만 가능하다면 어떻게 구현되어도 상관 없다는 요구사항임
}

protocol BProtocol{
    // 타입 프로퍼티를 요구하려면 static 키워드를 사용함.
    // 클래스의 타입 프로퍼티에는 상속 가능한 타입 프로퍼티인 class 타입 프로퍼티와
    // 상속 불가능한 static 타입 프로퍼티가 있으나!
    // 이 두 타입 프로퍼티를 따로 구분하지 않고 static 키워드를 사용하여 프로퍼티를 요구하면 됨
    static var c: Int { get set }
    static var d: Int { get }
    // c, d 모두 타입 프로퍼티 요구하는 중
}
protocol Talkable {
    var topic: String { get set }
    // 이 프로토콜은 어떤 주제에 말할 수 있게 하는 프로퍼티인 topic 을 요구함
}
struct person: Talkable {
    var topic: String
    // 그래서 위 프로토콜을 채택하여 준수하는 Person 클래스는 topic 프로퍼티를 가져야함
}

메서드 요구

protocol Talkable {
    var topic: String { get set }
    func talk(to: person)
    //프로토콜이 요구할 메서드는 프로토콜 정의에서 작성,
    //다만 실제 구현부인 중괄호({}) 부분은 제외하고 메서드의 이름, 매개변수, 반환 타입 등만 작성함
    //그리고 매개변수 기본값을 지정할 수 없음
    //static 키워드를 사용하여 요구한 타입 메서드를 클래스에서 실제 구현할 대에는 static 키워드나
    //class 키워드 어느 쪽을 사용해도 무방함
}

struct person: Talkable {
    func talk(to: person) {
        print("\(topic)에 대히 \(to.name)에게 이야기합니다.")
    }//

    var topic: String
    var name: String
}

이니셜라이저 요구

protocol Talkable {
    var topic: String { get set }
    func talk(to: Person)
    init(name: String, topic: String)// 정의는 하지만 구현은 X, 매개변수만
}
struct Person: Talkable {
    var topic: String
    var name: String

    func talk(to: Person){
        print("\(topic)에 대해 \(to.name)에게 이야기합니다.")
    }
    init(name: String, topic: String) {
        self.name = name
        self.topic = topic
    }
}

let cat: Person = Person(name: "고양이", topic: "집사")
let sister: Person = Person(name: "언니", topic: "가족")

cat.talk(to: sister)// -> 집사에 대해 언니에게 이야기합니다.

프로토콜의 상속

protocol Readable {
    func read()
}
protocol Writeable {
    func write()
}
protocol ReadSpeakable: Readable {
    func speak() //상속
}
protocol ReadWriteSpeakable: Readable, Writeable {
    func speak() // 상속의 상속
}

class SomeClass: ReadWriteSpeakable {
    func read() {
        print("Read")
    }

    func write() {
        print("Write")
    }

    func speak() {
        print("Speak")
    }
}

하나 이상의 프로토콜을 상속받고, 기존 프로토콜의 요구사항보다 더 많은 요구사항을 추가할 수 있음

참조

Swift – 프로토콜, 익스텐션

ronick-grammer commented 11 months ago

Protocol 이란

protocol A {
    var variable: Int { get set } // getter or getter/setter 를 명시해 줘야한다.

    func A()
}

protocol B {
...
}

protocol C {
...
}

protocol A: B, C {
    var variable: Int { get set }

    func A()
}
protocol A {
    var variableA: Int { get set }

    func A()
}

extension A {

    var variableA: Int {
        return 10
    }

    func A() {
        print(variableA)
    }
}
protocol A {
    associatedtype Element

    var variableA: Element { get set }

    func A() -> Element
}

📝 참고 사이트