Skip to content

Instantly share code, notes, and snippets.

@nataliapanferova
Created May 5, 2024 11:40
Show Gist options
  • Select an option

  • Save nataliapanferova/df1c4ff678c717b3d62614b59d3c9461 to your computer and use it in GitHub Desktop.

Select an option

Save nataliapanferova/df1c4ff678c717b3d62614b59d3c9461 to your computer and use it in GitHub Desktop.
Swift tips
// 1. - Iterate over items and indices in collections
var ingredients = ["potatoes", "cheese", "cream"]
for (i, ingredient) in ingredients.enumerated() {
// The counter helps us display the sequence number, not the index
print("ingredient number \(i + 1) is \(ingredient)")
}
// Array<String>.SubSequence
var doubleIngredients = ingredients.dropFirst()
for (i, ingredient) in zip(
doubleIngredients.indices, doubleIngredients
) {
// Correctly use the actual indices of the subsequence
doubleIngredients[i] = "\(ingredient) x 2"
}
import Algorithms
for (i, ingredient) in doubleIngredients.indexed() {
// Do something with the index
doubleIngredients[i] = "\(ingredient) x 2"
}
// 2. - Label loop statements to control execution of nested loops
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
let valueToFind = 5
searchValue: for row in matrix {
for num in row {
if num == valueToFind {
print("Value \(valueToFind) found!")
break searchValue
}
}
}
// 3. - Overload the pattern matching operator for custom matching behavior
struct Circle {
var radius: Double
}
func ~= (pattern: Double, value: Circle) -> Bool {
return value.radius == pattern
}
let myCircle = Circle(radius: 5)
switch myCircle {
case 5:
print("Circle with a radius of 5")
case 10:
print("Circle with a radius of 10")
default:
print("Circle with a different radius")
}
func ~= (pattern: ClosedRange<Double>, value: Circle) -> Bool {
return pattern.contains(value.radius)
}
switch myCircle {
case 0:
print("Radius is 0, it's a point!")
case 1...10:
print("Small circle with a radius between 1 and 10")
default:
print("Circle with a different radius")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment