Cannot assign to 'X' in 'Y' in Swift

后端 未结 3 665
-上瘾入骨i
-上瘾入骨i 2021-02-05 07:04

I have a dictionary with Structs in it. I am trying to assign the values of the struct when I loop through the dictionary. Swift is tellin

3条回答
  •  鱼传尺愫
    2021-02-05 08:08

    If 'Y' in this case is a protocol, subclass your protocol to class. I had a protocol:

     protocol PlayerMediatorElementProtocol {
          var playerMediator:PlayerMediator { get }
     }
    

    and tried to set playerMediator from within my player mediator:

    element.playerMediator = self
    

    Which turned into the error cannot asign 'playerMediator' in 'element'

    Changing my protocol to inherit from class fixed this issue:

     protocol PlayerMediatorElementProtocol : class {
          var playerMediator:PlayerMediator { get }
     }
    

    Why should it inherit from class?

    The reason it should inherit from class is because the compiler doesn't know what kind your protocol is inherited by. Structs could also inherit this protocol and you can't assign to a property of a constant struct.

提交回复
热议问题