1

I have the following protocol

protocol Three {
    var a1: Bool { get }
    var a2: Bool { get }
    var c1: Int { get }
    func test()
}

I then have a struct conforming to this protocol

struct ThreeTest: Three {
    var text: String
    
    init(_ text: String) {
        self.text = text
    }
}

// A
extension ThreeTest {
    var a1: Bool {
        return true
    }
    
    var a2: Bool {
        return true
    }
}

// B
extension ThreeTest {
    func test() {
        print("test")
    }
}

// C
extension ThreeTest {
    var c1: Int {
        return 10
    }
}

This is how I use it:

struct ViewModel {
    var three: Three
    
    init() {
        three = ThreeTest("hello")
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let vm = ViewModel()
        print("all good")
    }
}

This works fine and prints all good to the console.

What I do next is to split the protocol into multiple protocols and combine them using a typealias

protocol A {
    var a1: Bool { get }
    var a2: Bool { get }
}

protocol B {
    func test()
}

protocol C {
    var c1: Int { get }
}

typealias Three = A & B & C

If you run this in a test app, you will see this compiles and works fine as well with no issues, however, this exact same thing crashes my app with Thread 1: EXC_BAD_ACCESS (code=2, address=0x102b7ff38)

While I am aware that you will not be able to give me a fix for my situation as you do not have enough info and cannot reproduce do

My question is, What happens differently behind the scenes at run time when you have one protocol vs splitting the same requirements into multiple protocols and combining multiple protocols using typealias ?

Shawn Frank
  • 4,381
  • 2
  • 19
  • 29
  • @Sweeper - this is what I mentioned, this code runs fine on its own so you won't be able to reproduce. My question was - what is different that happens during run time when using one protocol vs. combining multiple protocols using typealis. – Shawn Frank Jun 07 '23 at 02:26
  • From looking at the assembly output difference using godbolt.org ([without -O](https://www.diffchecker.com/MZR8BsHL/) and [with -O](https://www.diffchecker.com/6k9SNSYV/)), it appears that using a typealias of the intersection type takes up more memory generally. – Sweeper Jun 07 '23 at 02:44
  • Have you also tried `protocol Three: A, B, C {}`? [This post](https://stackoverflow.com/q/74232417/5133585) could be related. – Sweeper Jun 07 '23 at 02:45

0 Answers0