Skip to content

Instantly share code, notes, and snippets.

@sodastsai
Last active May 24, 2018 04:47
Show Gist options
  • Save sodastsai/f34d4ed703a28a7e2749547fd19de4ea to your computer and use it in GitHub Desktop.
Save sodastsai/f34d4ed703a28a7e2749547fd19de4ea to your computer and use it in GitHub Desktop.
infix operator ?=: AssignmentPrecedence
infix operator ??=: AssignmentPrecedence
func ?= <T>(lhs: inout T, rhs: T?) {
print("-- ?= start")
defer { print("-- ?= end") }
guard let actualRhs = rhs else { return }
lhs = actualRhs
}
func ??= <T>(lhs: inout T, rhs: T?) {
print("-- ??= start")
defer { print("-- ??= end") }
lhs = rhs ?? lhs
}
struct Book {
var title: String {
didSet { print("Book.title:didSet called with '\(title)'") }
}
var author: String {
get {
print("Book.author:getter called")
return "default author"
}
set {
print("Book.author:setter called with '\(newValue)'")
}
}
}
let optionalTitle1: String? = nil
let optionalTitle2: String? = "banana"
print("------------")
var book1 = Book(title: "apple")
book1.title ?= optionalTitle1
print("book1 title is '\(book1.title)'")
book1.title ?= optionalTitle2
print("book1 title is '\(book1.title)'")
print("------------")
var book2 = Book(title: "apple")
book2.author ?= optionalTitle1
book2.author ?= optionalTitle2
print("------------")
var book3 = Book(title: "apple")
book3.title ??= optionalTitle1
book3.title ??= optionalTitle2
print("------------")
var book4 = Book(title: "apple")
book4.author ??= optionalTitle1
book4.author ??= optionalTitle2
// Console output:
/*
------------
-- ?= start
-- ?= end
Book.title:didSet called with 'apple'
book1 title is 'apple'
-- ?= start
-- ?= end
Book.title:didSet called with 'banana'
book1 title is 'banana'
------------
Book.author:getter called
-- ?= start
-- ?= end
Book.author:setter called with 'default author'
Book.author:getter called
-- ?= start
-- ?= end
Book.author:setter called with 'banana'
------------
-- ??= start
-- ??= end
Book.title:didSet called with 'apple'
-- ??= start
-- ??= end
Book.title:didSet called with 'banana'
------------
Book.author:getter called
-- ??= start
-- ??= end
Book.author:setter called with 'default author'
Book.author:getter called
-- ??= start
-- ??= end
Book.author:setter called with 'banana'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment