Instantly share code, notes, and snippets.

Embed
What would you like to do?
whats-new-in-swift-4.2
// SE-0194 Derived Collection of Enum Cases
enum CarType : CaseIterable {
case sedan
case crossover
case hothatch
case muscle
case miniVan
}
print(CarType.allCases.count)
//Conditional Conformance
let arrayOfArrays = [[1,2],[3,4],[5,6]]
arrayOfArrays.contains([1,2]) // now it returns True because of fact that the elements in the array conforms to Equatable protocol
let s: Set<[Int?]> = [[1,nil,2], [3,4], [5, nil,nil]]
s.contains([1,nil,2]) // returns true
// Hashable protocol
struct City {
let name: String
let state: String
}
extension City : Hashable {
func hash(into hasher: inout Hasher) {
name.hash(into: &hasher)
state.hash(into: &hasher)
}
}
let warsaw = City(name: "Warsaw", state: "Mazowieckie")
let cracow = City(name: "Kraków", state: "Małopolskie")
print(warsaw.hashValue)
print(cracow.hashValue)
// Generating Random numbers
let randomIntFrom0To20 = Int.random(in: 0 ..< 20)
let randomFloat = Float.random(in: 0 ..< 1)
let names = ["John", "Paul", "Peter", "Tim"]
names.randomElement()! // you need to unwrap the randomElement, because of the case where we call `randomElement` on empty collection.
names.shuffled()
let playerNumberToName : [Int: String] = [9: "Lewandowski", 7: "Ronaldo"]
playerNumberToName.randomElement()
let emptyCollection : [String] = []
emptyCollection.randomElement() // retuns nil
// Bool toggle
var isTheWeatherNice : Bool = true
print(isTheWeatherNice)
//now it's starts to rain
isTheWeatherNice.toggle()
print(isTheWeatherNice)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment