Coding Tests in Swift
Division
source: hackingwithswift.com
While
Same as do-while loop
For
Swift for Loop (with Examples)
Range requires lowerBound <= upperBound
Dict
Set
Accessing the value of a Swift Dict will return Optional.
let weeks = 465 / 7print("There are (weeks) weeks until the event.")// 66let weeks: Double = 465 / 7print("There are (weeks) weeks until the event.")// 66.42857142857143let weeks = 465 / 7let days = 465 % 7print("There are (weeks) weeks and (days) days until the event.")while (condition){ // body of loop}repeat { // body of loop} while (condition)// access items of an arraylet languages = ["Swift", "Java", "Go", "JavaScript"]
for language in languages { print(language)}// iterate from i = 1 to 1 = 3for i in 1...3 { print(i)}for i in stride(from: 1, to: 10, by: 2) { print(i)}// creating empty dictvar someDict = [KeyType: ValueType]()
// creating prefilled dictvar someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
// filteringvar closeCities = cityDistanceDict.filter { $0.value < 1000 }
// Grouping an Array
var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"]var GroupedCities = Dictionary(grouping: cities ) { $0.first! }// ["D" :["Delhi","Dehradun"], "B" : ["Bengaluru","Bihar"], "H" : ["Hyderabad"]]
// removesomeDict.removeValue(forKey: 2)// or simplysomeDict[2] = nil
// enumeratevar myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]for (idx, (key, value)) in myDictionary.enumerated() { print("(idx): key is (key), value is (value)")}let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]if ingredients.contains("sugar") { print("No thanks, too sweet.")}
// when init-ing empty set, must configure the typeSet<Int>()
.isEmpty.count.insertlet shortNames = cast.filter { $0.count < 5 }
// removingvar ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]let toRemove = "sugar"if let removed = ingredients.remove(toRemove) { print("The recipe is now (removed)-free.")}list.popLast();list.remove(at: <Int>list.insert(newElement: <Int>, at: <Int>)var hello = "Hello World!"
for (idx, char) in hello.enumerated() { print(char)}let strings = ["John", "Paul", "George", "Ringo"]let uppercased = strings.map { $0.uppercased() }type(of: char)starts.sort()
// sort by custom functionimages.sorted { $0.fileId > $1.fileID }string[String.Index(encodedOffset: index)]Array(coordinates[..<k]) // first k elements