Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use with block configure in Swift #786

Open
onmyway133 opened this issue Feb 28, 2021 · 0 comments
Open

How to use with block configure in Swift #786

onmyway133 opened this issue Feb 28, 2021 · 0 comments
Labels

Comments

@onmyway133
Copy link
Owner

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant