Swift 4.1 – What’s new

In a Nutshell

Swift 4.1 has arrived, with some minor changes that will alleviate some pain.
So, among the other things, here is a quick list of what you need to now.

Synthesized Equatable and Hashable

A default implementation for Equatable and Hashable interfaces was added.
Now, by default, two Equatable objects will be considered equal if all their properties are equal.

Swift 4.0 Example

// Some equatable class
class Fruit: Equatable {
	var kind: String
	var owner: String

	init(ofKind kind: String, ownedBy owner: String) {
		self.owner = owner
		self.kind = kind

// Needed to compare Fruit instances
func ==(l: Fruit, r: Fruit) -> Bool {
	return l.owner == r.owner && l.kind == r.kind

Swift 4.1 Example

// Some equatable class
class Fruit: Equatable {
	// Same as Swift 4.0

Test, working in both examples

// Example
let apple = Fruit(named: "Apple")
let banana = Fruit(named: "Banana")
let apple2 = Fruit(named: "Apple")

// "Apple" != "Banana", will print false
print("\(apple == banana)")

// "Apple" == "Apple", will print true
print("\(apple == apple2)")

You can still define your own equality method of course.

Conditional conformance

Conditional conformance has been extended to the Codable protocol.
This means that we can now compare Optional, Array, Dictionary, and Set object if their content is Codable.

Example working in Swift 4.1

let a: [String] = ["a", "aa", "aaa"]
let b: [String] = ["b", "bb", "bbb"]
print("\(a == b)")


Functional programming is a great tool, and compactMap just made life a bit easier.
In short, compactMap works just like flatMap, but will strip nil results.

Swift 4.0 + map

let values: [String] = ["1", "2", "aaa", "4"]

let numbersAndNils: [Int?] = values.map { Int($0) }
// [1, 2, nil, 4]

let numbersOnly: [Int] = (numbersAndNils.filter { $0 != nil }) as! [Int]
// [1, 2, 4]

Swift 4.1 + compactMap

let values: [String] = ["1", "2", "aaa", "4"]
let numbersOnly: [Int] = values.compactMap { Int($0) })
// [1, 2, 4]


Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...

Questo sito utilizza Akismet per ridurre lo spam. Scopri come vengono elaborati i dati derivati dai commenti.