What’s new in Swift 3.1 | Part 1

There are few backend-compatible updates in Swift 3.0. Idea is to cleaning up few advanced features for major release coming up in June 2017 – Swift 4.0.

Concrete Constrained Extensions:

Swift provide a way to extend the types using constraints which the most beautiful way to add functionality. here is an example.

extension Collection where Iterator.Element: Comparable   {
func greaterThanFist() -> [Iterator.Element] {
        guard let firstObject = self.first else { return []  }
        return self.filter  {   $0 > firstObject   }
    }
}


Here the idea is to get the greater elements compare with the first element and that code extends a protocols comparable only where it matches the constraint (This is most powerful stuff alone here) Swift 3.0 lets us extend a concrete type. But what if we wanted to go in more detail i mean only in case of Int array? so we can achieve it now.

extension Array where Element == Int {
    func greaterThanFist() -> [Int] {
        guard let firstObject = self.first else { return [] }
        return self.filter { $0 < firstObject }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s