ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Swift] ν”„λ‘œν† μ½œ(protocol)
    iOS/Swift 2022. 8. 31. 23:57

     

     

    πŸ’‘ ν”„λ‘œν† μ½œ

    - νŠΉμ • 역할을 ν•˜κΈ° μœ„ν•œ λ©”μ„œλ“œ, ν”„λ‘œνΌν‹° λ“±μ˜ 청사진이닀(μ±„νƒλ°›λŠ” νƒ€μž…μ΄ κ΅¬ν˜„μ„ μ•½μ†ν•œλ‹€)

    - ν”„λ‘œν† μ½œμ€ κ΅¬ν˜„λΆ€ {}κ°€ μ—†κΈ° λ•Œλ¬Έμ— λ‹¨λ…μœΌλ‘œ μ‚¬μš©μ΄ λΆˆκ°€ν•˜λ‹€ -> 클래슀, ꡬ쑰체와 ν•¨κ»˜ μ‚¬μš©

    - ν”„λ‘œν† μ½œμ„ μ‚¬μš©ν•˜λ©΄ 클래슀, ꡬ쑰체 λ“± λ‹€λ₯Έ νƒ€μž…μ΄λ”λΌλ„ 같은 μΈν„°νŽ˜μ΄μŠ€λ‘œ λ‹€μ–‘ν•œ κ΅¬ν˜„μ΄ κ°€λŠ₯ν•˜λ‹€!

     

    ν”„λ‘œν† μ½œ μ •μ˜

    protocol ν”„λ‘œν† μ½œ 이름 {
        ν”„λ‘œν† μ½œ μ •μ˜
    }

     

    ν”„λ‘œν† μ½œ 채택

    // ꡬ쑰체, 클래슀, μ—΄κ±°ν˜•μ—μ„œμ˜ κ΅¬ν˜„ 방법
    
    struct SomeStruct: AProtocol, AnotherProtocol {
        // ꡬ쑰체 μ •μ˜
    }
    
    class SomeClass: AProtocol, AnotherProtocol {
        // 클래슀 μ •μ˜
    }
    
    enum SomeEnum: AProtocol, AnotherProtocol {
        // μ—΄κ±°ν˜• μ •μ˜

     

    ν”„λ‘œν† μ½œμ˜ ν”„λ‘œνΌν‹° μš”κ΅¬

    ν”„λ‘œν† μ½œμ€ μžμ‹ μ„ μ±„νƒν•œ νƒ€μž…μ΄ μ–΄λ–€ ν”„λ‘œνΌν‹°λ₯Ό κ΅¬ν˜„ν•΄μ•Ό ν•˜λŠ”μ§€ μš”κ΅¬ν•  수 μžˆλ‹€!

     

    ⭐️ ν”„λ‘œνΌν‹° μš”κ΅¬μ‚¬ν•­μ€ 항상 var ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•œ λ³€μˆ˜ ν”„λ‘œνΌν‹°λ‘œ μ •μ˜

     

    - 읽기/μ“°κΈ° λͺ¨λ‘ κ°€λŠ₯ν•œ ν”„λ‘œνΌν‹°: {get set}

    - 읽기 μ „μš© ν”„λ‘œνΌν‹°: {get}

    - μ“°κΈ° μ „μš© ν”„λ‘œνΌν‹°: ❌

     

    ⭐️ νƒ€μž… ν”„λ‘œνΌν‹°λ₯Ό μš”κ΅¬ν•˜κΈ° μœ„ν•΄μ„  static ν‚€μ›Œλ“œ μ‚¬μš©

     

    ** νƒ€μž… ν”„λ‘œνΌν‹°(static): μΈμŠ€ν„΄μŠ€(객체)κ°€ 생성될 λ•Œ λ§ˆλ‹€ 각 μΈμŠ€ν„΄μŠ€μ— ν• λ‹Ήλ˜λŠ” ν”„λ‘œνΌν‹°μ™€ λ‹€λ₯΄κ²Œ ν•΄λ‹Ή νƒ€μž…μœΌλ‘œ μƒμ„±λœ λͺ¨λ“  μΈμŠ€ν„΄μŠ€μ—μ„œ μ‚¬μš©ν•˜λŠ” 단 ν•˜λ‚˜μ˜ ν”„λ‘œνΌν‹°(μ΄λ‹ˆμ…œλΌμ΄μ €βŒ)

     

    protocol SomeProtocol {
        var settableProperty: String { get set }
        var notNeedToBeSettableProperty: String { get }
    }
    protocol AnotherProtocol {
        static var someTypeProperty: Int { get set }
        static var anotherTypeProperty: Int { get }
    }

     

    μ΄λ‹ˆμ…œλΌμ΄μ € μš”κ΅¬

    μ΄λ‹ˆμ…œλΌμ΄μ €μ˜ λ§€κ°œλ³€μˆ˜λ₯Ό μ§€μ •ν•˜λŠ” μ—­ν• λ§Œ μˆ˜ν–‰ν•˜κ³ , κ΅¬ν˜„μ€ ν•˜μ§€ μ•ŠλŠ”λ‹€

    ⭐️ required μ‹λ³„μžλ₯Ό 뢙인 μš”μ²­ μ΄λ‹ˆμ…œλΌμ΄μ €λ‘œ κ΅¬ν˜„
     protocol Talkable {
         var topic: String { get set }
         func talk(to: Person)
         init(name: String, topic: String)
     }

     

    ** λ§Œμ•½ 클래슀 μžμ²΄κ°€ 상속받을 수 μ—†λŠ” final 클래슀라면 required μ‹λ³„μž 뢙여쀄 ν•„μš”βŒ


    ⭐️ required와 override μ‹λ³„μž λͺ¨λ‘ λͺ…μ‹œ

    ** λ§Œμ•½ νŠΉμ • ν΄λž˜μŠ€μ— ν”„λ‘œν† μ½œμ΄ μš”κ΅¬ν•˜λŠ” μ΄λ‹ˆμ…œλΌμ΄μ €κ°€ 이미 μžˆλŠ” μƒν™©μ—μ„œ κ·Έ 클래슀λ₯Ό 상속받은 ν΄λž˜μŠ€κ°€ μžˆλ‹€λ©΄,

     

     

    클래슀 μ „μš© ν”„λ‘œν† μ½œ

    ν”„λ‘œν† μ½œμ˜ 상속 λ¦¬μŠ€νŠΈμ— class ν‚€μ›Œλ“œλ₯Ό μΆ”κ°€ν•˜μ—¬ 클래슀 νƒ€μž…μ—λ§Œ 채택될 수 μžˆλ„λ‘ μ œν•œν•œλ‹€

    protocol ν”„λ‘œν† μ½œλͺ…: class, Readable {
    }

     

     

     

     

     

Designed by Tistory.