Protocol: Cannot Assign “X” to “Y” in Swift

I just defined a very simple protocol and class using generics that can handle this protocol.

In the lines marked with an error, you will receive an error message: "Cannot assign flag" to "aObj.

protocol Flag { var flag: Bool {get set} } class TestFlag<T: Flag> { func toggle(aObj: T) { if aObj.flag { aObj.flag = false; // <--- error } else { aObj.flag = true; // <--- error } } } 

Do you have an idea why and what I need to change to fix this?

+6
source share
2 answers

From docs :

Functional parameters are constants by default. Attempting to change the value of a function parameter from the body of this function results in a compile-time error. This means that you cannot change the parameter value by mistake.

In this case, you can add inout to keep the switch outside your function call:

 func toggle(inout aObj: T) { if aObj.flag { aObj.flag = false; else { aObj.flag = true; } } 

You could also do:

 func toggle(var aObj: T) { } 

but it may not achieve what you wanted.

+6
source

manojlds answer is correct, and so I accepted it.

However, a few days ago there was a similar answer with the same solution, but with a different argument (now it is deleted).

The argument was that the compiler cannot know whether the protocol is used for a class, structure, or enumeration. With Swift, protocols can be applied to all of these types. But instances of the structure use a call by value, and for instances of classes (objects) it is a call by reference.

From my point of view, this answer was also correct, because you can solve the problem with the second solution:

 @objc protocol Flag { var flag: Bool {get set} } 

Just add @obj attriute to the protocol. As a result, you can use this protocol only for classes that produce results, only by-refernece calls are allowed. Therefore, the compiler no longer needs inout information.

But I was looking for a solution to increase protocol reuse and now using manojlds suggestions.

+2
source

Source: https://habr.com/ru/post/971186/


All Articles