Advertisement
Guest User

Untitled

a guest
Jul 29th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. //: Playground - noun: a place where people can play
  2.  
  3. import UIKit
  4.  
  5. var str = "Hello, playground"
  6.  
  7. class Hoge{
  8. let prop: String = "aaaaa"
  9.  
  10. func echoecho(){
  11. print("aaaaaa")
  12. }
  13. }
  14.  
  15. protocol HogeProtocol{
  16. var aaa: String { get set }
  17. }
  18.  
  19. class ImpHogeProtocol: HogeProtocol{
  20. var aaa: String = "aaaaa"
  21. }
  22.  
  23. /**
  24. * associatedTypeを試してみた。
  25. * 要は、assciatedTypeはprotocol版Generics
  26. * protocolではGenericsは基本使えない
  27. */
  28. protocol TestProtocol{
  29. associatedtype TestObject
  30.  
  31. func echosuru(by data:TestObject)
  32. }
  33.  
  34. // 以下はエラー
  35. //protocol TestProtocol2<T: HogeProtocol>{
  36. //
  37. //}
  38.  
  39.  
  40. class TestImplements: TestProtocol{
  41. typealias TestObject = Hoge
  42.  
  43. func echosuru(by data: Hoge) {
  44. print(data.prop)
  45. }
  46. }
  47.  
  48.  
  49. class TestImplements3: TestProtocol{
  50. typealias TestObject = ImpHogeProtocol
  51.  
  52. func echosuru(by data: ImpHogeProtocol) {
  53. print(data.aaa)
  54. }
  55. }
  56.  
  57. let obj = TestImplements()
  58. obj.echosuru(by: Hoge())
  59.  
  60. let obj2 = TestImplements3()
  61. obj2.echosuru(by: ImpHogeProtocol())
  62.  
  63.  
  64. protocol HogeHogeProtocol{
  65. var objHoge: Hoge { get set }
  66.  
  67. func hogehoge()
  68. }
  69.  
  70. extension HogeHogeProtocol{
  71.  
  72. var objHoge: Hoge{
  73. get{
  74. return objHoge
  75. }
  76. set{
  77. objHoge = newValue
  78. }
  79. }
  80.  
  81. func hogehoge(){
  82.  
  83. }
  84. }
  85.  
  86. // 以下はエラー
  87. /*
  88. extensionは変数定義が出来ないので、protocolとextensionだけだと、protocol
  89. に変数が多いと、実装するクラス全部で変数定義しないと行けないのが
  90. 超めんどくさい
  91. */
  92. // ベースクラスを用意して、protocolと併用して使うと、かなり便利に使える
  93. //extension HogeHogeProtocol{
  94. // var objHoge: Hoge = Hoge()
  95. //}
  96.  
  97. class HogeHogeProtocolImp: HogeHogeProtocol{
  98.  
  99. var objHoge: Hoge = Hoge()
  100.  
  101. func implTest(){
  102. objHoge.echoecho()
  103. }
  104. }
  105.  
  106. let objHogeHoge = HogeHogeProtocolImp()
  107. objHogeHoge.implTest()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement