swiftreactive-programmingreactive-swift

Swift tuple declaration in a protocol


I have a tuple variable in my code, that comes from ReactiveSwift:

class MyClass {
   var (signal, signalSender) = Signal<Bool, Error>.pipe()
}

How can I declare that variable tuple in a protocol?

Similar like this (doesn't work):

protocol MyProtocol {
   var (signal, signalSender): Signal<Bool, Error> { get set }
}

There appears a syntax error: "Getter/setter can only be defined for a single variable"

Thank you!


Solution

  • Type of your property should be tuple, not just declaration of some class/struct. So, look what your pipe() returns. It should return tuple with two types

    func pipe() -> (Type1, Type2) { ... }
    

    To protocol declaration use these two types

    protocol MyProtocol {
        var tuple: (signal: Type1, signalSender: Type2) { get set }
    }
    

    then implement this protocol to your class and assign it with return value of pipe()

    class MyClass: MyProtocol {
        var tuple: (signal: Type1, signalSender: Type2) = Signal<Bool, Error>.pipe() 
    }
    

    then when you need get element of tuple, just use

    tuple.signal
    tuple.signalSender