Skip to content

Instantly share code, notes, and snippets.

View mahmudahsan's full-sized avatar

Mahmud Ahsan mahmudahsan

View GitHub Profile
@mahmudahsan
mahmudahsan / error_handling5.swift
Created December 22, 2017 16:43
Error handling in swift
func square(val:Int) throws -> Int {
if val == 5 {
throw SampleError.sample1
}
return val * val
}
let sqaureValue = try! square(val: 10)
print(sqaureValue)
@mahmudahsan
mahmudahsan / error_handling4.swift
Created December 22, 2017 16:41
Error handling in swift
let str = try? sampleThrowError()
if let str = str {
print(str)
}
else {
print("Str is nil")
}
@mahmudahsan
mahmudahsan / error_handling3.swift
Created December 22, 2017 16:41
Error handling in swift
do {
try sampleThrowError()
}
catch SampleError.sample1 {
print("Sample 1 Error caught")
}
catch {
print("For all other cases")
}
@mahmudahsan
mahmudahsan / error_handling2.swift
Created December 22, 2017 16:40
Error handling in swift
func sampleThrowError() throws -> String {
throw SampleError.sample1
return ""
}
@mahmudahsan
mahmudahsan / error_handling1.swift
Created December 22, 2017 16:39
Error Handling in Swift
enum SampleError: Error {
case sample1
case sample2(message: String)
}
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let pairOfNumbers = [(2, 3), (5, 10), (4, 5)]
let operationQueue = OperationQueue()
//if set 1, it will be serial if commented it will be concurrent
operationQueue.maxConcurrentOperationCount = 1
let pairOfNumbers = [(2, 3), (5, 10), (4, 5)]
class MultiplcationOp : Operation{
var inputPair: [(Int, Int)]?
override func main() {
guard let inputPair = inputPair else { return }
for pair in inputPair{
let result = pair.0 * pair.1
print(result)
//Single BlockOperation
var result:Int?
let multiplication = BlockOperation{
result = 5 * 10
}
multiplication.start()
result
[/code]
Multiple operations using BlockOperation:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let workingQueue = DispatchQueue(label: "net.ithinkdiff.app", attributes: .concurrent)
let globalQueue = DispatchQueue.global()
let defaultGroup = DispatchGroup() //create a new group
func multiplication(_ num: (Int, Int)) -> Int{
sleep(1) //to make the method slower
import UIKit
import PlaygroundSupport
//to run serial queue in playground always make the following true
PlaygroundPage.current.needsIndefiniteExecution = true
let mainQueue = DispatchQueue.main
let globalQueue = DispatchQueue.global()
let serialQueue = DispatchQueue(label: "net.ithinkdiff.app")
let concurQueue = DispatchQueue(label: "net.ithinkdiff.app.concurr", attributes: .concurrent)