Skip to content

Instantly share code, notes, and snippets.

@vialyx
Last active April 25, 2018 07:00
Show Gist options
  • Save vialyx/de1887ba1d0b4f4f75459a88344a9465 to your computer and use it in GitHub Desktop.
Save vialyx/de1887ba1d0b4f4f75459a88344a9465 to your computer and use it in GitHub Desktop.
// MARK: Continue, break, throw
let numbers: [Int] = [1, 2, 3, 4, 5, 10, 11, 20]
// MARK: continue
var evenSum = 0
for number in numbers {
if number % 2 != 0 { continue }
evenSum += number
}
/*
Calculate sum of even numbers.
Skip not even numbers using 'continue' keyword.
*/
print("even summ: \(evenSum)")
// MARK: - break
var position = 0
let findNumber = 10
for (index, number) in numbers.enumerated() {
if number == findNumber {
position = index
break
}
}
/*
Find number position in array.
Stop loop using 'break' keyword when number has been found.
*/
print("number position: \(position)")
// MARK: return
enum MachingError: Error {
case NotEnoughtCharacters(count: Int)
}
enum CollectionError: Error {
case Empty
}
func joinKeys(lhs: String, rhs: String) throws -> String {
let minCount = 5
if lhs.isEmpty || rhs.isEmpty { throw CollectionError.Empty }
if lhs.count < minCount || rhs.count < minCount { throw MachingError.NotEnoughtCharacters(count: minCount) }
return lhs + rhs
}
do {
try joinKeys(lhs: "", rhs: "")
} catch is CollectionError {
print("empty")
} catch MachingError.NotEnoughtCharacters(let count) {
print("maching error min count: \(count)")
}
/*
That is better way than return nil value.
- Throwing works faster
- That is clear to understand when you receive CollectionError instead of nil result
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment