Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Created August 7, 2021 05:36
Show Gist options
  • Save JarvisTheAvenger/2bc451824d44f5940ef1276564ee3f67 to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/2bc451824d44f5940ef1276564ee3f67 to your computer and use it in GitHub Desktop.
import Foundation
// Error is protocol
// NSError is class
// NSError(domain: <#T##String#>, code: <#T##Int#>, userInfo: <#T##[String : Any]?#>)
enum BoardError : Error {
case failed
case resultPending
case unknown
}
class CBSE {
// Throwing function
func getScore(seatNumber: Int) throws -> Int {
let percentage = Int.random(in: 0...100)
if percentage < 35 {
throw BoardError.failed
} else {
return percentage
}
}
}
let exam = CBSE()
// Do-Try?-Catch or Do-Try!-Catch catch not allowed
// Error: block is unreachable because no errors are thrown in 'do' block
// Do-Try-Catch
do {
try exam.getScore(seatNumber: 23)
} catch {
print(error)
}
// Try?
let score = try? exam.getScore(seatNumber: 4)
// Try! - Avoid using it
let score1 = try? exam.getScore(seatNumber: 3)
// Multiple case catch statement
do {
try exam.getScore(seatNumber: 23)
} catch BoardError.failed, BoardError.resultPending {
print("your result is pending for evaluation!!!")
} catch {
print("unknown!!!")
}
// defer
func testDeferStatement() {
defer {
print(1)
}
defer {
print(2)
}
defer {
print(3)
}
do {
print(4)
}
do {
print(5)
}
}
testDeferStatement()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment