Skip to content

Instantly share code, notes, and snippets.

@dodikk
Last active December 1, 2016 15:40
Show Gist options
  • Save dodikk/d5d62002c6cf730c4b059215beeb9203 to your computer and use it in GitHub Desktop.
Save dodikk/d5d62002c6cf730c4b059215beeb9203 to your computer and use it in GitHub Desktop.
protocol and associated type test
//: Playground - noun: a place where people can play
import UIKit
protocol A
{
associatedtype SomeType
var a : SomeType { get }
}
protocol B : A
{
typealias SomeType = String
var a : String { get }
}
class C
{
// if uncommented, then it works. But we have a heavy dependency on `class AA`
// var ivar : AA? = nil
var ivar : B? = nil
}
class AA : A
{
var a: String = "hello"
}
var aa = AA()
var cc = C()
cc.ivar = aa
if let cIvar = cc.ivar
{
print(cIvar.a)
}
@dodikk
Copy link
Author

dodikk commented Dec 1, 2016

Version 1

Playground execution failed: error: ProtocolTest.playground:24:11: error: cannot assign value of type 'AA' to type 'B?'
cc.ivar = aa
          ^~

error: ProtocolTest.playground:26:10: error: value of type 'B?' has no member 'a'
print(cc.ivar.a)
      ~~~^~~~ ~

@dodikk
Copy link
Author

dodikk commented Dec 1, 2016

Version 3

Playground execution failed: error: ProtocolTest.playground:13:16: error: protocol 'B' can only be used as a generic constraint because it has Self or associated type requirements
    var ivar : B? = nil
               ^

error: ProtocolTest.playground:25:11: error: cannot assign value of type 'AA' to type 'B?'
cc.ivar = aa
          ^~

error: ProtocolTest.playground:27:10: error: value of optional type 'B?' not unwrapped; did you mean to use '!' or '?'?
print(cc.ivar.a)
         ^
             ?

@soxjke
Copy link

soxjke commented Dec 1, 2016

protocol A {
    associatedtype SomeType
    var a : SomeType { get }
}

class B<ResolutionType> : A {
    var a: ResolutionType? = nil
}

class C {
    var ivar : B<String>? = nil
}

class AA : B<String>
{
    override init() {
        super.init()
        a = "Hello"
    }
}

var aa = AA()
var cc = C()

cc.ivar = aa

print(cc.ivar?.a)

@dodikk
Copy link
Author

dodikk commented Dec 1, 2016

Made the thing compile but no classes can be injected.

// if uncommented, then it works. But we have a heavy dependency on `class AA`
//     var ivar : AA? = nil

@dodikk
Copy link
Author

dodikk commented Dec 1, 2016

class AA : B<String>

AA must be a sub-class of A since they belong to a third-party library in my case. And I can't change the hierarchy, I'm afraid.
P.S. They are Store class and Store protocol of the ReSwift library

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment