Issue with `Protocol can only be used as a generic constraint because it has Self or associated type...











up vote
3
down vote

favorite












I'm trying to generate a ViewModel that conforms to a Protocol Protocoling, the protocol is generic, and has an associated type.
There are a few ViewModel's that conform to the protocol, so I am trying to create a factory for the viewModel.
I have encotuntered the following error by Swift:
Protocol can only be used as a generic constraint because it has Self or associated type requirements
Example code:



protocol Protocoling {
associatedtype modulingType
var data: modulingType { get }
}

enum MyTypes {
case myName
case myAddress
}

class NameViewModel: Protocoling {
let data: String

init(name: String) {
data = name
}
}

class AddressViewModel: Protocoling {
let data: [String]
init(address: [String]) {
data = address
}
}

class DataFactory {
func viewModel(forType type: MyTypes) -> Protocoling {
switch type {
case .name: return NameViewModel(name: "Gil")
case .address: return AddressViewModel(address: ["Israel", "Tel Aviv"])
}
}
}


The error is in func viewModel(forType type: MyTypes) -> Protocoling.



Is there a way to solve this issue?










share|improve this question






















  • From the current example I think a factory model is not the best one. Maybe you could consider another way of doing it? For example using an enum with associated values (see docs.swift.org/swift-book/LanguageGuide/Enumerations.html).
    – Qbyte
    Nov 11 at 10:22










  • @Qbyte I thought about it, but the enum represents a state in my flow, And according to the state I initialise a ViewModel, the thing is, I don't want to bound the enum to a viewModel.
    – Gil Polak
    Nov 11 at 11:07















up vote
3
down vote

favorite












I'm trying to generate a ViewModel that conforms to a Protocol Protocoling, the protocol is generic, and has an associated type.
There are a few ViewModel's that conform to the protocol, so I am trying to create a factory for the viewModel.
I have encotuntered the following error by Swift:
Protocol can only be used as a generic constraint because it has Self or associated type requirements
Example code:



protocol Protocoling {
associatedtype modulingType
var data: modulingType { get }
}

enum MyTypes {
case myName
case myAddress
}

class NameViewModel: Protocoling {
let data: String

init(name: String) {
data = name
}
}

class AddressViewModel: Protocoling {
let data: [String]
init(address: [String]) {
data = address
}
}

class DataFactory {
func viewModel(forType type: MyTypes) -> Protocoling {
switch type {
case .name: return NameViewModel(name: "Gil")
case .address: return AddressViewModel(address: ["Israel", "Tel Aviv"])
}
}
}


The error is in func viewModel(forType type: MyTypes) -> Protocoling.



Is there a way to solve this issue?










share|improve this question






















  • From the current example I think a factory model is not the best one. Maybe you could consider another way of doing it? For example using an enum with associated values (see docs.swift.org/swift-book/LanguageGuide/Enumerations.html).
    – Qbyte
    Nov 11 at 10:22










  • @Qbyte I thought about it, but the enum represents a state in my flow, And according to the state I initialise a ViewModel, the thing is, I don't want to bound the enum to a viewModel.
    – Gil Polak
    Nov 11 at 11:07













up vote
3
down vote

favorite









up vote
3
down vote

favorite











I'm trying to generate a ViewModel that conforms to a Protocol Protocoling, the protocol is generic, and has an associated type.
There are a few ViewModel's that conform to the protocol, so I am trying to create a factory for the viewModel.
I have encotuntered the following error by Swift:
Protocol can only be used as a generic constraint because it has Self or associated type requirements
Example code:



protocol Protocoling {
associatedtype modulingType
var data: modulingType { get }
}

enum MyTypes {
case myName
case myAddress
}

class NameViewModel: Protocoling {
let data: String

init(name: String) {
data = name
}
}

class AddressViewModel: Protocoling {
let data: [String]
init(address: [String]) {
data = address
}
}

class DataFactory {
func viewModel(forType type: MyTypes) -> Protocoling {
switch type {
case .name: return NameViewModel(name: "Gil")
case .address: return AddressViewModel(address: ["Israel", "Tel Aviv"])
}
}
}


The error is in func viewModel(forType type: MyTypes) -> Protocoling.



Is there a way to solve this issue?










share|improve this question













I'm trying to generate a ViewModel that conforms to a Protocol Protocoling, the protocol is generic, and has an associated type.
There are a few ViewModel's that conform to the protocol, so I am trying to create a factory for the viewModel.
I have encotuntered the following error by Swift:
Protocol can only be used as a generic constraint because it has Self or associated type requirements
Example code:



protocol Protocoling {
associatedtype modulingType
var data: modulingType { get }
}

enum MyTypes {
case myName
case myAddress
}

class NameViewModel: Protocoling {
let data: String

init(name: String) {
data = name
}
}

class AddressViewModel: Protocoling {
let data: [String]
init(address: [String]) {
data = address
}
}

class DataFactory {
func viewModel(forType type: MyTypes) -> Protocoling {
switch type {
case .name: return NameViewModel(name: "Gil")
case .address: return AddressViewModel(address: ["Israel", "Tel Aviv"])
}
}
}


The error is in func viewModel(forType type: MyTypes) -> Protocoling.



Is there a way to solve this issue?







ios swift






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 9:00









Gil Polak

1218




1218












  • From the current example I think a factory model is not the best one. Maybe you could consider another way of doing it? For example using an enum with associated values (see docs.swift.org/swift-book/LanguageGuide/Enumerations.html).
    – Qbyte
    Nov 11 at 10:22










  • @Qbyte I thought about it, but the enum represents a state in my flow, And according to the state I initialise a ViewModel, the thing is, I don't want to bound the enum to a viewModel.
    – Gil Polak
    Nov 11 at 11:07


















  • From the current example I think a factory model is not the best one. Maybe you could consider another way of doing it? For example using an enum with associated values (see docs.swift.org/swift-book/LanguageGuide/Enumerations.html).
    – Qbyte
    Nov 11 at 10:22










  • @Qbyte I thought about it, but the enum represents a state in my flow, And according to the state I initialise a ViewModel, the thing is, I don't want to bound the enum to a viewModel.
    – Gil Polak
    Nov 11 at 11:07
















From the current example I think a factory model is not the best one. Maybe you could consider another way of doing it? For example using an enum with associated values (see docs.swift.org/swift-book/LanguageGuide/Enumerations.html).
– Qbyte
Nov 11 at 10:22




From the current example I think a factory model is not the best one. Maybe you could consider another way of doing it? For example using an enum with associated values (see docs.swift.org/swift-book/LanguageGuide/Enumerations.html).
– Qbyte
Nov 11 at 10:22












@Qbyte I thought about it, but the enum represents a state in my flow, And according to the state I initialise a ViewModel, the thing is, I don't want to bound the enum to a viewModel.
– Gil Polak
Nov 11 at 11:07




@Qbyte I thought about it, but the enum represents a state in my flow, And according to the state I initialise a ViewModel, the thing is, I don't want to bound the enum to a viewModel.
– Gil Polak
Nov 11 at 11:07












1 Answer
1






active

oldest

votes

















up vote
0
down vote













You can use a protocol with an associated type (PAT) as a return type like that without more constraint because the compiler needs to know which type to use.



In your case you must use a technic called the type erasure to be able to work with any Protocoling:



class AnyProtocoling: Protocoling {
let data: Any

init<U: Protocoling>(_ viewModel: U) {
self.data = viewModel.data as Any
}
}

class DataFactory {
func viewModel(forType type: MyTypes) -> AnyProtocoling {
switch type {
case .myName:
return AnyProtocoling(NameViewModel(name: "Gil"))
case .myAddress:
return AnyProtocoling(AddressViewModel(address: ["Israel", "Tel Aviv"]))
}
}
}


This will allow you to "erase" the associated type of your protocol and return an Any version of your view model.



In order to understand why the PAT needs to work like that I like the following example: the Equatable protocol (which is a PAT):



static func ==(lhs: Self, rhs: Self) -> Bool


This function uses the Self type which is an associated type. You want to use it in the next generic function:



func areEquals(left: Equatable, right: Equatable) -> Bool {
return left == right
}


Here the compiler will trigger this error: Protocol can only be used as a generic constraint because it has Self or associated type requirements. Why? Lets take this example:



struct tomato: Equatable {}
struct salad: Equatable {}

areEquals(left: tomato(), right: salad())


There is no reason to compare tomatoes and salads. The associated type Self is not the same. To avoid this error in this case you need to constraint the Self type as following:



func areEquals<T: Equatable>(left: T, right: T) -> Bool


Now you know the T are equatables and with the same associated types.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53247217%2fissue-with-protocol-can-only-be-used-as-a-generic-constraint-because-it-has-sel%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    You can use a protocol with an associated type (PAT) as a return type like that without more constraint because the compiler needs to know which type to use.



    In your case you must use a technic called the type erasure to be able to work with any Protocoling:



    class AnyProtocoling: Protocoling {
    let data: Any

    init<U: Protocoling>(_ viewModel: U) {
    self.data = viewModel.data as Any
    }
    }

    class DataFactory {
    func viewModel(forType type: MyTypes) -> AnyProtocoling {
    switch type {
    case .myName:
    return AnyProtocoling(NameViewModel(name: "Gil"))
    case .myAddress:
    return AnyProtocoling(AddressViewModel(address: ["Israel", "Tel Aviv"]))
    }
    }
    }


    This will allow you to "erase" the associated type of your protocol and return an Any version of your view model.



    In order to understand why the PAT needs to work like that I like the following example: the Equatable protocol (which is a PAT):



    static func ==(lhs: Self, rhs: Self) -> Bool


    This function uses the Self type which is an associated type. You want to use it in the next generic function:



    func areEquals(left: Equatable, right: Equatable) -> Bool {
    return left == right
    }


    Here the compiler will trigger this error: Protocol can only be used as a generic constraint because it has Self or associated type requirements. Why? Lets take this example:



    struct tomato: Equatable {}
    struct salad: Equatable {}

    areEquals(left: tomato(), right: salad())


    There is no reason to compare tomatoes and salads. The associated type Self is not the same. To avoid this error in this case you need to constraint the Self type as following:



    func areEquals<T: Equatable>(left: T, right: T) -> Bool


    Now you know the T are equatables and with the same associated types.






    share|improve this answer

























      up vote
      0
      down vote













      You can use a protocol with an associated type (PAT) as a return type like that without more constraint because the compiler needs to know which type to use.



      In your case you must use a technic called the type erasure to be able to work with any Protocoling:



      class AnyProtocoling: Protocoling {
      let data: Any

      init<U: Protocoling>(_ viewModel: U) {
      self.data = viewModel.data as Any
      }
      }

      class DataFactory {
      func viewModel(forType type: MyTypes) -> AnyProtocoling {
      switch type {
      case .myName:
      return AnyProtocoling(NameViewModel(name: "Gil"))
      case .myAddress:
      return AnyProtocoling(AddressViewModel(address: ["Israel", "Tel Aviv"]))
      }
      }
      }


      This will allow you to "erase" the associated type of your protocol and return an Any version of your view model.



      In order to understand why the PAT needs to work like that I like the following example: the Equatable protocol (which is a PAT):



      static func ==(lhs: Self, rhs: Self) -> Bool


      This function uses the Self type which is an associated type. You want to use it in the next generic function:



      func areEquals(left: Equatable, right: Equatable) -> Bool {
      return left == right
      }


      Here the compiler will trigger this error: Protocol can only be used as a generic constraint because it has Self or associated type requirements. Why? Lets take this example:



      struct tomato: Equatable {}
      struct salad: Equatable {}

      areEquals(left: tomato(), right: salad())


      There is no reason to compare tomatoes and salads. The associated type Self is not the same. To avoid this error in this case you need to constraint the Self type as following:



      func areEquals<T: Equatable>(left: T, right: T) -> Bool


      Now you know the T are equatables and with the same associated types.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        You can use a protocol with an associated type (PAT) as a return type like that without more constraint because the compiler needs to know which type to use.



        In your case you must use a technic called the type erasure to be able to work with any Protocoling:



        class AnyProtocoling: Protocoling {
        let data: Any

        init<U: Protocoling>(_ viewModel: U) {
        self.data = viewModel.data as Any
        }
        }

        class DataFactory {
        func viewModel(forType type: MyTypes) -> AnyProtocoling {
        switch type {
        case .myName:
        return AnyProtocoling(NameViewModel(name: "Gil"))
        case .myAddress:
        return AnyProtocoling(AddressViewModel(address: ["Israel", "Tel Aviv"]))
        }
        }
        }


        This will allow you to "erase" the associated type of your protocol and return an Any version of your view model.



        In order to understand why the PAT needs to work like that I like the following example: the Equatable protocol (which is a PAT):



        static func ==(lhs: Self, rhs: Self) -> Bool


        This function uses the Self type which is an associated type. You want to use it in the next generic function:



        func areEquals(left: Equatable, right: Equatable) -> Bool {
        return left == right
        }


        Here the compiler will trigger this error: Protocol can only be used as a generic constraint because it has Self or associated type requirements. Why? Lets take this example:



        struct tomato: Equatable {}
        struct salad: Equatable {}

        areEquals(left: tomato(), right: salad())


        There is no reason to compare tomatoes and salads. The associated type Self is not the same. To avoid this error in this case you need to constraint the Self type as following:



        func areEquals<T: Equatable>(left: T, right: T) -> Bool


        Now you know the T are equatables and with the same associated types.






        share|improve this answer












        You can use a protocol with an associated type (PAT) as a return type like that without more constraint because the compiler needs to know which type to use.



        In your case you must use a technic called the type erasure to be able to work with any Protocoling:



        class AnyProtocoling: Protocoling {
        let data: Any

        init<U: Protocoling>(_ viewModel: U) {
        self.data = viewModel.data as Any
        }
        }

        class DataFactory {
        func viewModel(forType type: MyTypes) -> AnyProtocoling {
        switch type {
        case .myName:
        return AnyProtocoling(NameViewModel(name: "Gil"))
        case .myAddress:
        return AnyProtocoling(AddressViewModel(address: ["Israel", "Tel Aviv"]))
        }
        }
        }


        This will allow you to "erase" the associated type of your protocol and return an Any version of your view model.



        In order to understand why the PAT needs to work like that I like the following example: the Equatable protocol (which is a PAT):



        static func ==(lhs: Self, rhs: Self) -> Bool


        This function uses the Self type which is an associated type. You want to use it in the next generic function:



        func areEquals(left: Equatable, right: Equatable) -> Bool {
        return left == right
        }


        Here the compiler will trigger this error: Protocol can only be used as a generic constraint because it has Self or associated type requirements. Why? Lets take this example:



        struct tomato: Equatable {}
        struct salad: Equatable {}

        areEquals(left: tomato(), right: salad())


        There is no reason to compare tomatoes and salads. The associated type Self is not the same. To avoid this error in this case you need to constraint the Self type as following:



        func areEquals<T: Equatable>(left: T, right: T) -> Bool


        Now you know the T are equatables and with the same associated types.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 9:58









        Yannick Loriot

        5,94622545




        5,94622545






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53247217%2fissue-with-protocol-can-only-be-used-as-a-generic-constraint-because-it-has-sel%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Full-time equivalent

            Bicuculline

            さくらももこ