반응형
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// protocol(프로토콜) | |
// 이름 붙이는 방식은 보통 ~able, ~ing, ~delegate | |
protocol Naming { | |
var name: String { get <#set#> } | |
func getName() -> String | |
} | |
//프로토콜 상속 | |
struct Friend : Naming{ | |
var name: String | |
func getName() -> String { | |
return "이름은 \(name)입니다." | |
} | |
} | |
var myFreind = Friend(name: "예티") | |
myFreind.getName() | |
결과 | |
"이름은 예티입니다." |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// protocol(프로토콜)의 상속 | |
protocol Naming { | |
var name: String { get set } | |
func getName() -> String | |
} | |
protocol Aging { | |
var age: Int { get set } | |
} | |
protocol UserNotifiable: Naming, Aging { } | |
struct MyFriend: UserNotifiable { | |
func getName() -> String { | |
return "이름은 \(name)이고, 나이는 \(age)살 입니다." | |
} | |
var name: String | |
var age: Int | |
} | |
var myFreind = MyFriend(name: "예티", age: 5) | |
myFreind.getName() | |
결과 | |
"이름은 예티이고, 나이는 5살 입니다." |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// protocol(프로토콜)의 확장 | |
protocol Naming { | |
var lastName: String { get set } | |
var firstName: String { get set } | |
func getName() -> String | |
} | |
// 프로토콜이 로직을 가지게 할 수 있다. | |
extension Naming { | |
func getFullName() -> String { | |
return self.lastName + " " + self.firstName | |
} | |
} | |
struct Friend: Naming { | |
var lastName: String | |
var firstName: String | |
func getName() -> String { | |
return self.lastName | |
} | |
} | |
let myFriend = Friend(lastName: "가", firstName: "나다 ") | |
myFriend.getName() | |
myFriend.getFullName() | |
결과 | |
"가" | |
"가나다" |
반응형
'iOS > Swift문법' 카테고리의 다른 글
[Swift 문법] 프로토콜 associatedType - day12 (0) | 2022.04.05 |
---|---|
[Swift 문법] 콜렉션 Set - day11 (0) | 2022.03.31 |
[Swift 문법] 에러 - day10 (0) | 2022.03.19 |
[Swift 문법] 매개변수 inout - day9 (0) | 2022.03.17 |
[Swift 문법] 딕셔너리(Dictionary) - day8 (0) | 2022.03.15 |