| Sep | OCT | Nov |
| 18 | ||
| 2019 | 2020 | 2021 |
COLLECTED BY
Collection: General Crawls
struct Player {
var name: String
var highScore: Int = 0
var history: [Int] = []
init(_ name: String) {
self.name = name
}
}
var player = Player("Tomas")
Declare new types with modern, straightforward syntax. Provide default values for instance properties and define custom initializers.
extension Player {
mutating func updateScore(_ newScore: Int) {
history.append(newScore)
if highScore < newScore {
print("\(newScore)! A new high score for \(name)! 🎉")
highScore = newScore
}
}
}
player.updateScore(50)
// Prints "50! A new high score for Tomas! 🎉"
// player.highScore == 50
Add functionality to existing types using extensions, and cut down on boilerplate with custom string interpolations.
extension Player: Codable, Equatable {}
import Foundation
let encoder = JSONEncoder()
try encoder.encode(player)
print(player)
// Prints "Tomas, games played: 1, high score: 50”
Quickly extend your custom types to take advantage of powerful language features, such as automatic JSON encoding and decoding.
let players = getPlayers()
// Sort players, with best high scores first
let ranked = players.sorted(by: { player1, player2 in
player1.highScore > player2.highScore
})
// Create an array with only the players’ names
let rankedNames = ranked.map { $0.name }
// ["Erin", "Rosana", "Tomas"]
Perform powerful custom transformations using streamlined closures.
These forward-thinking concepts result in a language that is fun and easy to use.
Swift has many other features to make your code more expressive:
●Generics that are powerful and simple to use
●Protocol extensions that make writing generic code even easier
●First class functions and a lightweight closure syntax
●Fast and concise iteration over a range or collection
●Tuples and multiple return values
●Structs that support methods, extensions, and protocols
●Enums can have payloads and support pattern matching
●Functional programming patterns, e.g., map and filter
●Native error handling using try / catch / throw
extension Collection where Element == Player {
// Returns the highest score of all the players,
// or `nil` if the collection is empty.
func highestScoringPlayer() -> Player? {
return self.max(by: { $0.highScore < $1.highScore })
}
}
Use optionals when you might have an instance to return from a function, or you might not.
if let bestPlayer = players.highestScoringPlayer() {
recordHolder = """
The record holder is \(bestPlayer.name),\
with a high score of \(bestPlayer.highScore)!
"""
} else {
recordHolder = "No games have been played yet.")
}
print(recordHolder)
// The record holder is Erin, with a high score of 271!
let highestScore = players.highestScoringPlayer()?.highScore??0
// highestScore == 271
Features such as optional binding, optional chaining, and nil coalescing let you work safely and efficiently with optional values.