SA
메인 내용으로 이동

Coding Tests in Swift

Division

source: hackingwithswift.com

let weeks = 465 / 7
print("There are (weeks) weeks until the event.")
// 66
let weeks: Double = 465 / 7
print("There are (weeks) weeks until the event.")
// 66.42857142857143
let weeks = 465 / 7
let days = 465 % 7
print("There are (weeks) weeks and (days) days until the event.")

While

while (condition){
// body of loop
}
repeat {
// body of loop
} while (condition)

Same as do-while loop

For

Swift for Loop (with Examples)

// access items of an array
let languages = ["Swift", "Java", "Go", "JavaScript"]

for language in languages {
print(language)
}
// iterate from i = 1 to 1 = 3
for i in 1...3 {
print(i)
}

Range requires lowerBound <= upperBound

for i in stride(from: 1, to: 10, by: 2) {
print(i)
}

Dict

Swift - Dictionaries

// creating empty dict
var someDict = [KeyType: ValueType]()

// creating prefilled dict
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

// filtering
var 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"]]

// remove
someDict.removeValue(forKey: 2)
// or simply
someDict[2] = nil

// enumerate
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
for (idx, (key, value)) in myDictionary.enumerated() {
print("(idx): key is (key), value is (value)")
}

Set

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 type
Set<Int>()

.isEmpty
.count
.insert
let shortNames = cast.filter { $0.count < 5 }

// removing
var ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
let toRemove = "sugar"
if let removed = ingredients.remove(toRemove) {
print("The recipe is now (removed)-free.")
}

Accessing the value of a Swift Dict will return Optional.

Stacks and Queues

list.popLast();
list.remove(at: <Int>
list.insert(newElement: <Int>, at: <Int>)

Iterate String in Swift

var hello = "Hello World!"

for (idx, char) in hello.enumerated() {
print(char)
}

Map an Array

let strings = ["John", "Paul", "George", "Ringo"]
let uppercased = strings.map { $0.uppercased() }

Checking Type

type(of: char)

Sort

starts.sort()

// sort by custom function
images.sorted { $0.fileId > $1.fileID }

String Index

string[String.Index(encodedOffset: index)]

Array Cut

Array(coordinates[..<k]) // first k elements