gotnull
gotnull

Reputation: 27214

Conditional if statement in Swift

I came across a conditional if statement in Objective-C:

self.frontCardView = self.backCardView;
if ((self.backCardView = [self popPersonViewWithFrame:[self backCardViewFrame]])) {
    // Fade the back card into view.
    ...
}

Basically:

if ((self.backCardView = self.popPersonViewWithFrame(self.backCardViewFrame()))) {...}

This sets "self.backCardView" to the return value of "-popPersonViewWithFrame:". In C (and Objective-C), the result of an assignment is the assigned value.

In this case, the result of the expression "(self.backCardView = [self popPersonViewWithFrame:self.backCardViewFrame])" the return value of "-popPersonViewWithFrame:".

If the return value is "nil", then the conditional is not executed (since "nil" is a false value).

If I try to do the same thing in Swift:

self.frontCardView = self.backCardView
if ((self.backCardView = self.popPersonViewWithFrame(self.backCardViewFrame()))) {
    // Fade the back card into view.
    ...
}

I get an error in compilation:

Type '()' does not conform to protocol 'LogicValue'

Upvotes: 0

Views: 2560

Answers (4)

Tim
Tim

Reputation: 14446

Assign, then check for nil separately.

self.frontCardView = self.backCardView
self.backCardView = self.popPersonViewWithFrame(self.backCardViewFrame())
if self.backCardView != nil {
    // Fade the back card into view.
    // ...
}

Upvotes: 1

NRitH
NRitH

Reputation: 13893

The condition isn't a condition, so like Bryan Chen said, do the assignment outside of the condition, but assign it to another variable. In the condition, then, check whether that variable is equal to backCardView, like so:

frontCardView = backCardView
let poppedView = self.popPersonViewWithFrame(self.backCardViewFrame())
if backCardView == poppedView {
    // Fade the back card into view.
    ...

Upvotes: 1

Connor
Connor

Reputation: 64644

() is simply a typealias for void, which is what assignments return in Swift. As Bryan suggested, just put the assignment outside of the condition.

Upvotes: 1

drewag
drewag

Reputation: 94713

Swift was specifically designed to not allow testing an assignment in a conditional for safety reasons (people accidentally using one = instead of two). The result of an assignment operator is always void () like the error says.

Upvotes: 2

Related Questions