Skip to content

Instantly share code, notes, and snippets.

@reddavis
Last active March 14, 2023 08:30
Show Gist options
  • Save reddavis/73637c91b7ea1290219857076cc7aacb to your computer and use it in GitHub Desktop.
Save reddavis/73637c91b7ea1290219857076cc7aacb to your computer and use it in GitHub Desktop.
infix operator ||=
func ||=<T>(lhs: inout T?, rhs: T) {
guard lhs == nil else { return }
lhs = rhs
}
import XCTest
final class OrEqualsTests: XCTestCase {
func test_orEquals() {
var int: Int?
int ||= 1
XCTAssertEqual(int, 1)
int = 2
int ||= 3
XCTAssertEqual(int, 2)
var dictionary: [Int : Int] = [1 : 1]
dictionary[2] ||= 2
XCTAssertEqual(dictionary[2], 2)
dictionary[1] ||= 5
XCTAssertEqual(dictionary[1], 1)
XCTAssertEqual(dictionary, [1 : 1, 2 : 2])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment