Vince O'Sullivan
Vince O'Sullivan

Reputation: 2701

Swift playground prints parentheses

Xcode 7.2, Swift 2.0: The code below prints "15 ()" in the debug area. I would have expected it to print "15 1". Why are the parentheses being printed?

var n = 15
print(n, n /= 10)

Upvotes: 3

Views: 728

Answers (2)

Cristik
Cristik

Reputation: 32775

That's because the n /= 15 expression returns a Void, because the /= operator returns Void in Swift. We can see that from it's declaration:

public func /=<T : _IntegerArithmeticType>(inout lhs: T, rhs: T)

And because in Swift, Void is an alias for the empty tuple:

/// The empty tuple type.
///
/// This is the default return type of functions for which no explicit
/// return type is specified.
public typealias Void = ()

the second argument/expression passed to print gets printed as ().

Upvotes: 5

Michael Ramos
Michael Ramos

Reputation: 5817

Because there is nothing returned from an assignment operator. It is still executed though.

See docs here: Swift Docs

The assignment operator (=) does not return a value, to prevent it from being mistakenly used when the equal to operator (==) is intended.

Upvotes: 2

Related Questions