onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
675 stars 33 forks source link

How to use with block configure in Swift #786

Open onmyway133 opened 3 years ago

onmyway133 commented 3 years ago

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

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.

with(book) {
    name = updatedBook.name
    page = updatedBook.page
    publishedAt = updatedBook.publishedAt
}

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

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

[book].forEach {
    $0.name = updatedBook.name
    $0.page = updatedBook.page
    $0.publishedAt = updatedBook.publishedAt
}