Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: Playground - noun: a place where people can play
- import UIKit
- var str = "Hello, playground"
- class Hoge{
- let prop: String = "aaaaa"
- func echoecho(){
- print("aaaaaa")
- }
- }
- protocol HogeProtocol{
- var aaa: String { get set }
- }
- class ImpHogeProtocol: HogeProtocol{
- var aaa: String = "aaaaa"
- }
- /**
- * associatedTypeを試してみた。
- * 要は、assciatedTypeはprotocol版Generics
- * protocolではGenericsは基本使えない
- */
- protocol TestProtocol{
- associatedtype TestObject
- func echosuru(by data:TestObject)
- }
- // 以下はエラー
- //protocol TestProtocol2<T: HogeProtocol>{
- //
- //}
- class TestImplements: TestProtocol{
- typealias TestObject = Hoge
- func echosuru(by data: Hoge) {
- print(data.prop)
- }
- }
- class TestImplements3: TestProtocol{
- typealias TestObject = ImpHogeProtocol
- func echosuru(by data: ImpHogeProtocol) {
- print(data.aaa)
- }
- }
- let obj = TestImplements()
- obj.echosuru(by: Hoge())
- let obj2 = TestImplements3()
- obj2.echosuru(by: ImpHogeProtocol())
- protocol HogeHogeProtocol{
- var objHoge: Hoge { get set }
- func hogehoge()
- }
- extension HogeHogeProtocol{
- var objHoge: Hoge{
- get{
- return objHoge
- }
- set{
- objHoge = newValue
- }
- }
- func hogehoge(){
- }
- }
- // 以下はエラー
- /*
- extensionは変数定義が出来ないので、protocolとextensionだけだと、protocol
- に変数が多いと、実装するクラス全部で変数定義しないと行けないのが
- 超めんどくさい
- */
- // ベースクラスを用意して、protocolと併用して使うと、かなり便利に使える
- //extension HogeHogeProtocol{
- // var objHoge: Hoge = Hoge()
- //}
- class HogeHogeProtocolImp: HogeHogeProtocol{
- var objHoge: Hoge = Hoge()
- func implTest(){
- objHoge.echoecho()
- }
- }
- let objHogeHoge = HogeHogeProtocolImp()
- objHogeHoge.implTest()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement