قالب وردپرس درنا توس
Home / IOS Development / Swift Tips: An Example Refactoring

Swift Tips: An Example Refactoring



Last week's tips, we showed you a typical refactoring from our Swift project on the server as we continue to send Swift Talk backend from Ruby to Swift. This week we follow another useful refactoring.

To retrieve all episodes for a collection, we have a simple method in an extension. Similarly, we have a calculated property that calculates total duration of all episodes in the collection:

  extension Collection {
func episodes () -> [Episode] {
return Episode.all.filter {$ 0.collections.contains (id)}
}

var totalDuration: TimeInterval {
return episodes.map {$ 0.mediaDuration} .reduce (0, +)
}
}

These implementations are not completed; they do not take into account the user's role. For example, we will hide the unpublished episodes from regular users, and only show them to administrators.

We Refactored Episodes () Method Slow:

  Extension Collection {
func episodes (for user: UserData?) -> [Episode] {
return Episode.scoped (for: user) .filter {$ 0.collections.contains (id)}
}
}

We also need to change total value from a calculated property to a method:

  extension Collection {
func totalDuration (for user: UserData?) -> TimeInterval {
return episodes (for: user) .map {$ 0.mediaDuration} .reduce (0, +)
}
}

However, it feels a little wrong to transfer the user directly. What about other calculated properties that depend on episodes? After thinking about it, we removed totality (for :) from our extension and rewritten it as follows:

  extension Sequence where element == episode {
var totalDuration: TimeInterval {
return card {$ 0.mediaDuration} .reduce (0, +)
}
}

This changes our call page: instead of collection.totalDuration (for: user) we may write collection.episodes (for: user) .totalDuration .

The good thing about this implementation is that we can now use functionality elsewhere ̵

1; for example, we can use it when we show total duration of all episodes on Swift Talk. We can also easily add more calculated properties to the limited extension on Sequence without transferring the user everywhere.

If you like such refactorings, check out Swift Talk, our weekly live encoding video series. We do them often! 😊


Source link