How to use with block configure in Swift

Issue #786

Sometimes we need to update some properties between objects, for example

1
2
3
book.name = updatedBook.name
book.page = updatedBook.page
book.publishedAt = updatedBook.publishedAt

Repeating the caller book is tedious and error-prone. In Kotlin, there is with block which is handy to access the receiver properties and methods without referring to it.

1
2
3
4
5
with(book) {
name = updatedBook.name
page = updatedBook.page
publishedAt = updatedBook.publishedAt
}

In Swift, there are no such thing, we can write some extension like

1
2
3
4
5
6
7
extension Book {
func update(with anotherBook: Book) {
name = anotherBook.name
page = anotherBook.page
publishedAt = anotherBook.publishedAt
}
}

Or simply, we can just use forEach with just that book

1
2
3
4
5
[book].forEach {
$0.name = updatedBook.name
$0.page = updatedBook.page
$0.publishedAt = updatedBook.publishedAt
}

Comments