├── ConcurrencyIsHard.playground ├── Resources │ ├── train_day.jpg │ ├── train_dusk.jpg │ ├── razeware_64.png │ ├── train_night.jpg │ └── dark_road_small.jpg ├── Duration.remap ├── GradientGenerator.remap ├── contents.xcplayground ├── TiltShift.remap ├── NetworkSimulator.remap ├── Sources │ ├── Duration.swift │ ├── NetworkSimulator.swift │ ├── TiltShift.swift │ └── Graphics │ │ ├── GradientGenerator.swift │ │ └── UIImage+Blur.swift ├── Pages │ ├── Dispatch Barriers.xcplaygroundpage │ │ ├── Sources │ │ │ ├── Delay.swift │ │ │ └── Person.swift │ │ └── Contents.swift │ ├── Operations in Practice.xcplaygroundpage │ │ ├── Sources │ │ │ ├── ImageLoader.swift │ │ │ ├── AsyncOperation.swift │ │ │ ├── ImageFilters.swift │ │ │ └── ImageCell.swift │ │ └── Contents.swift │ ├── Operation Dependencies.xcplaygroundpage │ │ ├── Sources │ │ │ └── AsyncOperation.swift │ │ └── Contents.swift │ ├── Operation.xcplaygroundpage │ │ └── Contents.swift │ ├── OperationQueue.xcplaygroundpage │ │ └── Contents.swift │ ├── Dispatch Groups.xcplaygroundpage │ │ └── Contents.swift │ ├── GCD.xcplaygroundpage │ │ └── Contents.swift │ ├── Async Operations.xcplaygroundpage │ │ └── Contents.swift │ └── Futures.xcplaygroundpage │ │ └── Contents.swift └── UIImage+Blur.remap ├── README.md └── .gitignore /ConcurrencyIsHard.playground/Resources/train_day.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/2017AtSwift_Concurrency/HEAD/ConcurrencyIsHard.playground/Resources/train_day.jpg -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Resources/train_dusk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/2017AtSwift_Concurrency/HEAD/ConcurrencyIsHard.playground/Resources/train_dusk.jpg -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Resources/razeware_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/2017AtSwift_Concurrency/HEAD/ConcurrencyIsHard.playground/Resources/razeware_64.png -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Resources/train_night.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/2017AtSwift_Concurrency/HEAD/ConcurrencyIsHard.playground/Resources/train_night.jpg -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Resources/dark_road_small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sammyd/2017AtSwift_Concurrency/HEAD/ConcurrencyIsHard.playground/Resources/dark_road_small.jpg -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Duration.remap: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Duration.swift", 4 | "offset": 1158, 5 | "text": "_ ", 6 | } 7 | ] 8 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/GradientGenerator.remap: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/GradientGenerator.swift", 4 | "offset": 1158, 5 | "text": "_ ", 6 | } 7 | ] 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Concurrency on iOS 2 | 3 | This playground accompanies the talk I presented at @Swift 2017. 4 | 5 | It requires Xcode 8 or later, although no guarantees that the syntax hasn't changed since I wrote it. 6 | 7 | Any questions then say hi - [@iwantmyrealname](https://twitter.com/iwantmyrealname). 8 | 9 | much love! 10 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/TiltShift.remap: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/TiltShift.swift", 4 | "offset": 1154, 5 | "text": "_ ", 6 | }, 7 | { 8 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/TiltShift.swift", 9 | "offset": 1226, 10 | "remove": 1, 11 | "text": "n", 12 | }, 13 | { 14 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/TiltShift.swift", 15 | "offset": 1368, 16 | "text": "_ ", 17 | }, 18 | { 19 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/TiltShift.swift", 20 | "offset": 1416, 21 | "remove": 2, 22 | }, 23 | { 24 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/TiltShift.swift", 25 | "offset": 1447, 26 | "remove": 9, 27 | } 28 | ] 29 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/NetworkSimulator.remap: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/NetworkSimulator.swift", 4 | "offset": 1169, 5 | "text": "_ ", 6 | }, 7 | { 8 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/NetworkSimulator.swift", 9 | "offset": 1251, 10 | "remove": 1, 11 | "text": "n", 12 | }, 13 | { 14 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/NetworkSimulator.swift", 15 | "offset": 1335, 16 | "text": "_ ", 17 | }, 18 | { 19 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/NetworkSimulator.swift", 20 | "offset": 1383, 21 | "remove": 2, 22 | }, 23 | { 24 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/NetworkSimulator.swift", 25 | "offset": 1414, 26 | "remove": 9, 27 | } 28 | ] 29 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Sources/Duration.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import Foundation 24 | 25 | public func duration(_ block: () -> ()) -> TimeInterval { 26 | let startTime = Date() 27 | block() 28 | return Date().timeIntervalSince(startTime) 29 | } 30 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Dispatch Barriers.xcplaygroundpage/Sources/Delay.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import Foundation 24 | 25 | func randomDelay(maxDuration: Double) { 26 | let randomWait = arc4random_uniform(UInt32(maxDuration * Double(USEC_PER_SEC))) 27 | usleep(randomWait) 28 | } 29 | 30 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Operations in Practice.xcplaygroundpage/Sources/ImageLoader.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | public class ImageLoadOperation: AsyncOperation { 26 | public var inputName: String? 27 | public var outputImage: UIImage? 28 | 29 | public override func main() { 30 | simulateAsyncNetworkLoadImage(named: self.inputName) { (image) in 31 | self.outputImage = image 32 | self.state = .Finished 33 | } 34 | } 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xcuserstate 23 | 24 | ## Obj-C/Swift specific 25 | *.hmap 26 | *.ipa 27 | *.dSYM.zip 28 | *.dSYM 29 | 30 | ## Playgrounds 31 | timeline.xctimeline 32 | playground.xcworkspace 33 | 34 | # Swift Package Manager 35 | # 36 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 37 | # Packages/ 38 | .build/ 39 | 40 | # CocoaPods 41 | # 42 | # We recommend against adding the Pods directory to your .gitignore. However 43 | # you should judge for yourself, the pros and cons are mentioned at: 44 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 45 | # 46 | # Pods/ 47 | 48 | # Carthage 49 | # 50 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 51 | # Carthage/Checkouts 52 | 53 | Carthage/Build 54 | 55 | # fastlane 56 | # 57 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 58 | # screenshots whenever they are needed. 59 | # For more information about the recommended setup visit: 60 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md 61 | 62 | fastlane/report.xml 63 | fastlane/Preview.html 64 | fastlane/screenshots 65 | fastlane/test_output 66 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Sources/NetworkSimulator.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | public func simulateNetworkLoadImage(named: String?) -> UIImage? { 26 | sleep(1) 27 | guard let named = named else { return .none } 28 | return UIImage(named: named) 29 | } 30 | 31 | 32 | public func simulateAsyncNetworkLoadImage(named: String?, callback: @escaping (UIImage?) -> ()) { 33 | OperationQueue().addOperation { 34 | let image = simulateNetworkLoadImage(named: named) 35 | callback(image) 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Sources/TiltShift.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | public func tiltShift(image: UIImage?) -> UIImage? { 26 | guard let image = image else { return .none } 27 | sleep(1) 28 | let mask = topAndBottomGradient(size: image.size) 29 | return image.applyBlur(radius: 6, maskImage: mask) 30 | } 31 | 32 | func tiltShiftAsync(image: UIImage?, callback: @escaping (UIImage?) ->()) { 33 | OperationQueue().addOperation { 34 | let result = tiltShift(image: image) 35 | callback(result) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Dispatch Barriers.xcplaygroundpage/Sources/Person.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | 24 | import Foundation 25 | 26 | open class Person { 27 | private var firstName: String 28 | private var lastName: String 29 | 30 | public init(firstName: String, lastName: String) { 31 | self.firstName = firstName 32 | self.lastName = lastName 33 | } 34 | 35 | open func changeName(firstName: String, lastName: String) { 36 | randomDelay(maxDuration: 0.2) 37 | self.firstName = firstName 38 | randomDelay(maxDuration: 1) 39 | self.lastName = lastName 40 | } 41 | 42 | open var name: String { 43 | return "\(firstName) \(lastName)" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Sources/Graphics/GradientGenerator.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | func topAndBottomGradient(size: CGSize, clearLocations: [CGFloat] = [0.35, 0.65], innerIntensity: CGFloat = 0.5) -> UIImage { 26 | 27 | let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) 28 | 29 | let colors = [ 30 | .white, 31 | UIColor(white: innerIntensity, alpha: 1.0), 32 | .black, 33 | UIColor(white: innerIntensity, alpha: 1.0), 34 | .white 35 | ].map { $0.cgColor } 36 | let colorLocations : [CGFloat] = [0, clearLocations[0], (clearLocations[0] + clearLocations[1]) / 2.0, clearLocations[1], 1] 37 | 38 | let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceGray(), colors: colors as CFArray, locations: colorLocations) 39 | 40 | let startPoint = CGPoint(x: 0, y: 0) 41 | let endPoint = CGPoint(x: 0, y: size.height) 42 | 43 | context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions()) 44 | let cgImage = context!.makeImage() 45 | 46 | return UIImage(cgImage: cgImage!) 47 | 48 | } 49 | 50 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Operation Dependencies.xcplaygroundpage/Sources/AsyncOperation.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | 24 | import Foundation 25 | 26 | open class AsyncOperation: Operation { 27 | public enum State: String { 28 | case Ready, Executing, Finished 29 | 30 | fileprivate var keyPath: String { 31 | return "is" + rawValue 32 | } 33 | } 34 | 35 | public var state = State.Ready { 36 | willSet { 37 | willChangeValue(forKey: newValue.keyPath) 38 | willChangeValue(forKey: state.keyPath) 39 | } 40 | didSet { 41 | didChangeValue(forKey: oldValue.keyPath) 42 | didChangeValue(forKey: state.keyPath) 43 | } 44 | } 45 | } 46 | 47 | 48 | extension AsyncOperation { 49 | // NSOperation Overrides 50 | override open var isReady: Bool { 51 | return super.isReady && state == .Ready 52 | } 53 | 54 | override open var isExecuting: Bool { 55 | return state == .Executing 56 | } 57 | 58 | override open var isFinished: Bool { 59 | return state == .Finished 60 | } 61 | 62 | override open var isAsynchronous: Bool { 63 | return true 64 | } 65 | 66 | override open func start() { 67 | if isCancelled { 68 | state = .Finished 69 | return 70 | } 71 | 72 | main() 73 | state = .Executing 74 | } 75 | 76 | open override func cancel() { 77 | state = .Finished 78 | } 79 | } 80 | 81 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Operations in Practice.xcplaygroundpage/Sources/AsyncOperation.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | 24 | import Foundation 25 | 26 | open class AsyncOperation: Operation { 27 | public enum State: String { 28 | case Ready, Executing, Finished 29 | 30 | fileprivate var keyPath: String { 31 | return "is" + rawValue 32 | } 33 | } 34 | 35 | public var state = State.Ready { 36 | willSet { 37 | willChangeValue(forKey: newValue.keyPath) 38 | willChangeValue(forKey: state.keyPath) 39 | } 40 | didSet { 41 | didChangeValue(forKey: oldValue.keyPath) 42 | didChangeValue(forKey: state.keyPath) 43 | } 44 | } 45 | } 46 | 47 | 48 | extension AsyncOperation { 49 | // Operation Overrides 50 | override open var isReady: Bool { 51 | return super.isReady && state == .Ready 52 | } 53 | 54 | override open var isExecuting: Bool { 55 | return state == .Executing 56 | } 57 | 58 | override open var isFinished: Bool { 59 | return state == .Finished 60 | } 61 | 62 | override open var isAsynchronous: Bool { 63 | return true 64 | } 65 | 66 | override open func start() { 67 | if isCancelled { 68 | state = .Finished 69 | return 70 | } 71 | 72 | main() 73 | state = .Executing 74 | } 75 | 76 | open override func cancel() { 77 | state = .Finished 78 | } 79 | } 80 | 81 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Operation.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | /*: 2 | # Concurrency on iOS 3 | ## @Swift 2017 4 | ## Sam Davies · [@iwantmyrealname](https://twitter.com/iwantmyrealname) 5 | 6 | This playground forms the basis of a talk presented at @Swift 2017, in Shenzhen, China. 7 | 8 | The following represents the pages contained within this playground 9 | 10 | - [Operation](Operation) 11 | - [OperationQueue](OperationQueue) 12 | - [Wrapping Aysnc Functions in Operation](Async%20Operations) 13 | - [Inter-Operation Dependencies](Operation%20Dependencies) 14 | - [Operations in Practice](Operations%20in%20Practice) 15 | - [Grand Central Dispatch](GCD) 16 | - [Dispatch Groups](Dispatch%20Groups) 17 | - [Dispatch Barriers](Dispatch%20Barriers) 18 | - [Futures](Futures) 19 | 20 | --- 21 | 22 | ## [NS]Operation 23 | 24 | `Operation` is a high-level abstraction that represents _"a unit of work"_. You can use this to wrap some sort of functionality, and then pass this off to be executed concurrently. 25 | */ 26 | 27 | import UIKit 28 | 29 | //: `tiltShift(image:)` is a function that applies a tilt-shift-like filter to a `UIImage`, and as such it's rather (artificially) slow. 30 | 31 | let image = UIImage(named: "dark_road_small.jpg") 32 | duration { 33 | let result = tiltShift(image: image) 34 | } 35 | 36 | 37 | var outputImage: UIImage? 38 | 39 | //: You can use the `BlockOperation` subclass of `Operation` to easily wrap some functionality. 40 | 41 | let myFirstOperation = BlockOperation { 42 | outputImage = tiltShift(image: image) 43 | } 44 | 45 | 46 | //: You can then execute this operation with the `start()` method: 47 | myFirstOperation.start() 48 | 49 | 50 | 51 | outputImage 52 | 53 | 54 | /*: 55 | Although `BlockOperation` has a very low bar for entry, it's not especially flexible. It's more usual to subclass `Operation` directly, and specialise it to particular functionality. 56 | 57 | When subclassing, create properties for input and output objects, and then override the `main()` method to perform the work. 58 | */ 59 | class TiltShiftOperation: Operation { 60 | var inputImage: UIImage? 61 | var outputImage: UIImage? 62 | 63 | override func main() { 64 | outputImage = tiltShift(image: inputImage) 65 | } 66 | } 67 | 68 | let mySecondOperation = TiltShiftOperation() 69 | mySecondOperation.inputImage = image 70 | 71 | 72 | 73 | /*: 74 | Once you've created an instance of the operation, and set the input value, you can go ahead and call `start()` to kick off the execution. 75 | 76 | - note: 77 | Calling `start()` might seem a little strange, but don't worry - you won't be doing it for long... 78 | 79 | */ 80 | mySecondOperation.start() 81 | 82 | mySecondOperation.outputImage 83 | 84 | 85 | //: [➡ OperationQueue](@next) 86 | 87 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/OperationQueue.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | /*: 2 | [⬅ Operation](@previous) 3 | 4 | ## [NS]OperationQueue 5 | 6 | There's not a lot of point of carefully wrapping up complex functionality in `Operation` objects if you then have to call `start()` on each of them to actually begin execution. 7 | 8 | Enter `OperationQueue`, which manages the execution of one or more `Operation` objects. Rather than having to handle threads directly, you instead pass your operations to a queue to be executed at the system's discretion. A queue can be configured to allow concurrent execution of the operations in the queue. 9 | 10 | */ 11 | 12 | import UIKit 13 | 14 | 15 | //: Using the same tilt-shift operation, this time you've got a set of images rather than just one: 16 | let imageNames = ["dark_road_small", "train_day", "train_dusk", "train_night"] 17 | 18 | let images = imageNames.flatMap { UIImage(named: "\($0).jpg") } 19 | images 20 | 21 | 22 | class TiltShiftOperation: Operation { 23 | var inputImage: UIImage? 24 | var outputImage: UIImage? 25 | 26 | override func main() { 27 | outputImage = tiltShift(image: inputImage) 28 | } 29 | } 30 | 31 | 32 | //: Creating a queue is simple - using the default constructor: 33 | let queue = OperationQueue() 34 | 35 | var operations = [TiltShiftOperation]() 36 | 37 | 38 | /*: 39 | Use the `addOperation()` method on `NSOperationQueue` to add each operation to the queue. 40 | 41 | - important: 42 | Adding operations to a queue is really "cheap"; although the operations can start executing as soon as they arrive on the queue, adding them is completely asynchronous. 43 | \ 44 | You can see that here, with the result of the `duration` function: 45 | 46 | */ 47 | 48 | duration { 49 | for image in images { 50 | let op = TiltShiftOperation() 51 | op.inputImage = image 52 | operations += [op] 53 | 54 | queue.addOperation(op) 55 | } 56 | } 57 | 58 | 59 | /*: 60 | * experiment: 61 | You can control the maximum number of operations that a queue can execute simultaneously with the `maxConcurrentOperationCount` property. Setting this to `1` makes the queue a *serial* queue. 62 | \ 63 | \ 64 | Try changing the value of this property below to see how it affects the time it takes for the queue to finish processing all operations. 65 | \ 66 | _You'll find that this doesn't actually work—you need to set this property __before__ you add the operations to the queue._ 67 | */ 68 | 69 | queue.maxConcurrentOperationCount = 1 70 | 71 | duration { 72 | queue.waitUntilAllOperationsAreFinished() 73 | } 74 | 75 | 76 | 77 | //: Check that all operations have filtered the image as expected 78 | let output = operations.flatMap { $0.outputImage } 79 | output[0] 80 | output[1] 81 | output[2] 82 | output[3] 83 | 84 | //: [➡ Operation Async](@next) 85 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Operations in Practice.xcplaygroundpage/Sources/ImageFilters.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | 24 | import UIKit 25 | 26 | 27 | public class TiltShiftOperation: Operation { 28 | public var inputImage: UIImage? 29 | public var outputImage: UIImage? 30 | 31 | public override func main() { 32 | if let dependencyImageProvider = dependencies 33 | .filter({ $0 is FilterDataProvider }) 34 | .first as? FilterDataProvider, 35 | inputImage == .none { 36 | inputImage = dependencyImageProvider.outputImage 37 | } 38 | 39 | outputImage = tiltShift(image: inputImage) 40 | } 41 | } 42 | 43 | public class ImageOutputOperation: Operation { 44 | public var inputImage: UIImage? 45 | public var completion: ((UIImage?) -> ())? 46 | 47 | public override func main() { 48 | guard let completion = completion else { return } 49 | if let dependencyImageProvider = dependencies 50 | .filter({ $0 is FilterDataProvider }) 51 | .first as? FilterDataProvider, 52 | inputImage == .none { 53 | inputImage = dependencyImageProvider.outputImage 54 | } 55 | 56 | completion(inputImage) 57 | } 58 | } 59 | 60 | 61 | 62 | public protocol FilterDataProvider { 63 | var outputImage: UIImage? { get } 64 | } 65 | 66 | extension ImageLoadOperation: FilterDataProvider { 67 | 68 | } 69 | 70 | extension TiltShiftOperation: FilterDataProvider { 71 | 72 | } 73 | 74 | precedencegroup Chainable { 75 | associativity: left 76 | } 77 | 78 | infix operator |> : Chainable 79 | 80 | public extension Operation { 81 | public static func |>(lhs: Operation, rhs: Operation) -> Operation { 82 | rhs.addDependency(lhs) 83 | return rhs 84 | } 85 | } 86 | 87 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Operations in Practice.xcplaygroundpage/Sources/ImageCell.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | 25 | public class ImageCell: UITableViewCell { 26 | public var fullImage: UIImage? { 27 | didSet { 28 | fullImageView?.image = fullImage 29 | } 30 | } 31 | 32 | public func transitionToImage(image: UIImage?) { 33 | OperationQueue.main.addOperation { 34 | if image == .none { 35 | self.fullImageView?.alpha = 0 36 | } else { 37 | self.fullImageView?.image = image 38 | UIView.animate(withDuration: 0.4) { 39 | self.fullImageView?.alpha = 1 40 | } 41 | } 42 | } 43 | } 44 | 45 | var fullImageView: UIImageView? 46 | 47 | required public init?(coder aDecoder: NSCoder) { 48 | super.init(coder: aDecoder) 49 | sharedInit() 50 | } 51 | 52 | override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { 53 | super.init(style: style, reuseIdentifier: reuseIdentifier) 54 | sharedInit() 55 | } 56 | 57 | 58 | func sharedInit() { 59 | fullImageView = UIImageView(image: fullImage) 60 | 61 | guard let fullImageView = fullImageView else { return } 62 | addSubview(fullImageView) 63 | 64 | fullImageView.contentMode = .scaleAspectFill 65 | fullImageView.translatesAutoresizingMaskIntoConstraints = false 66 | fullImageView.clipsToBounds = true 67 | 68 | NSLayoutConstraint.activate([ 69 | fullImageView.bottomAnchor.constraint(equalTo: bottomAnchor), 70 | fullImageView.topAnchor.constraint(equalTo: topAnchor), 71 | fullImageView.leadingAnchor.constraint(equalTo: leadingAnchor), 72 | fullImageView.trailingAnchor.constraint(equalTo: trailingAnchor) 73 | ]) 74 | 75 | } 76 | 77 | } 78 | 79 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Dispatch Barriers.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ GCD Groups](@previous) 2 | 3 | import Foundation 4 | import PlaygroundSupport 5 | 6 | PlaygroundPage.current.needsIndefiniteExecution = true 7 | 8 | //: ## GCD Barriers 9 | //: When you're using asynchronous calls you need to consider thread safety. 10 | //: Consider the following object: 11 | 12 | let nameChangingPerson = Person(firstName: "Alison", lastName: "Anderson") 13 | 14 | //: The `Person` class includes a method to change names: 15 | 16 | nameChangingPerson.changeName(firstName: "Brian", lastName: "Biggles") 17 | nameChangingPerson.name 18 | 19 | //: What happens if you try and use the `changeName(firstName:lastName:)` simulataneously from a concurrent queue? 20 | 21 | let workerQueue = DispatchQueue(label: "com.raywenderlich.worker", attributes: .concurrent) 22 | let nameChangeGroup = DispatchGroup() 23 | 24 | let nameList = [("Charlie", "Cheesecake"), ("Delia", "Dingle"), ("Eva", "Evershed"), ("Freddie", "Frost"), ("Gina", "Gregory")] 25 | 26 | for (idx, name) in nameList.enumerated() { 27 | workerQueue.async(group: nameChangeGroup) { 28 | usleep(UInt32(10_000 * idx)) 29 | nameChangingPerson.changeName(firstName: name.0, lastName: name.1) 30 | print("Current Name: \(nameChangingPerson.name)") 31 | } 32 | } 33 | 34 | nameChangeGroup.notify(queue: DispatchQueue.main) { 35 | print("Final name: \(nameChangingPerson.name)") 36 | //PlaygroundPage.current.finishExecution() 37 | } 38 | 39 | nameChangeGroup.wait() 40 | 41 | 42 | //: __Result:__ `nameChangingPerson` has been left in an inconsistent state. 43 | 44 | 45 | //: ### Dispatch Barrier 46 | //: A barrier allows you add a task to a concurrent queue that will be run in a serial fashion. i.e. it will wait for the currently queued tasks to complete, and prevent any new ones starting. 47 | 48 | class ThreadSafePerson: Person { 49 | let isolationQueue = DispatchQueue(label: "com.raywenderlich.person.isolation", attributes: .concurrent) 50 | 51 | override func changeName(firstName: String, lastName: String) { 52 | isolationQueue.async(flags: .barrier) { 53 | super.changeName(firstName: firstName, lastName: lastName) 54 | } 55 | } 56 | 57 | override var name: String { 58 | return isolationQueue.sync { 59 | return super.name 60 | } 61 | } 62 | } 63 | 64 | 65 | 66 | print("\n=== Threadsafe ===") 67 | 68 | let threadSafeNameGroup = DispatchGroup() 69 | 70 | let threadSafePerson = ThreadSafePerson(firstName: "Anna", lastName: "Adams") 71 | 72 | for (idx, name) in nameList.enumerated() { 73 | workerQueue.async(group: threadSafeNameGroup) { 74 | usleep(UInt32(10_000 * idx)) 75 | threadSafePerson.changeName(firstName: name.0, lastName: name.1) 76 | print("Current threadsafe name: \(threadSafePerson.name)") 77 | } 78 | } 79 | 80 | threadSafeNameGroup.notify(queue: DispatchQueue.main) { 81 | print("Final threadsafe name: \(threadSafePerson.name)") 82 | PlaygroundPage.current.finishExecution() 83 | } 84 | 85 | 86 | //: [➡ Futures](@next) 87 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Dispatch Groups.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ Grand Central Dispatch](@previous) 2 | /*: 3 | ## Dispatch Groups 4 | 5 | Dispatch groups are a feature of GCD that allow you to perform an action when a group of GCD operations has completed. This offers a really simple way to keep track of the progress of a set of operations, rather than having to implement something to keep track yourself. 6 | 7 | When you're responsible for dispatching blocks yourself, it's really easy to disptach a block into a particular dispatch group, using the `dispatch_group_*()` family of functions, but the real power comes from being able to wrap existing async functions in dispatch groups. 8 | 9 | In this demo you'll see how you can use dispatch groups to run an action when a set of disparate animations has completed. 10 | */ 11 | import UIKit 12 | import PlaygroundSupport 13 | 14 | //: Create a new animation function on `UIView` that wraps an existing animation function, but now takes a dispatch group as well. 15 | extension UIView { 16 | static func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void, group: DispatchGroup, completion: ((Bool) -> Void)?) { 17 | group.enter() 18 | animate(withDuration: duration, animations: animations) { (success) in 19 | completion?(success) 20 | group.leave() 21 | } 22 | } 23 | } 24 | 25 | 26 | //: Create a disptach group with `dispatch_group_create()`: 27 | let animationGroup = DispatchGroup() 28 | 29 | 30 | //: The animation uses the following views 31 | let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) 32 | view.backgroundColor = #colorLiteral(red: 0.6823074818, green: 0.08504396677, blue: 0.06545677781, alpha: 1) 33 | let box = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) 34 | box.backgroundColor = #colorLiteral(red: 0.4028071761, green: 0.7315050364, blue: 0.2071235478, alpha: 1) 35 | view.addSubview(box) 36 | 37 | PlaygroundPage.current.liveView = view 38 | 39 | //: The following completely independent animations now use the dispatch group so that you can determine when all of the animations have completed: 40 | UIView.animate(withDuration: 1, animations: { 41 | box.center = CGPoint(x: 150, y: 150) 42 | }, group: animationGroup, completion: { 43 | _ in 44 | UIView.animate(withDuration: 2, animations: { 45 | box.transform = CGAffineTransform(rotationAngle: .pi/4) 46 | }, group: animationGroup, completion: .none) 47 | }) 48 | 49 | UIView.animate(withDuration: 4, animations: { 50 | view.backgroundColor = #colorLiteral(red: 0.9898764491, green: 0.7441664934, blue: 0.1842373013, alpha: 1) 51 | }, group: animationGroup, completion: .none) 52 | 53 | 54 | //: `dispatch_group_notify()` allows you to specify a block that will be executed only when all the blocks in that dispatch group have completed: 55 | animationGroup.notify(queue: DispatchQueue.main) { 56 | print("Animations Completed!") 57 | //PlaygroundPage.current.finishExecution() 58 | } 59 | 60 | //: [➡ Thread safety with GCD Barriers](@next) 61 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/GCD.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ Operation in Practice](@previous) 2 | /*: 3 | ## GCD Queues 4 | [NS]Operation queues are built on top of a technology called `libdispatch`, or *Grand Central Dispatch*. This is an advanced open-source technology that underpins concurrent programming on Apple technologies. It uses the now-familiar queuing model to greatly simplify concurrent programming, up until recently via a C-level interface. However, Swift 3 has greatly improved the GCD API, so it's no longer nearly as challenging. 5 | */ 6 | import UIKit 7 | import PlaygroundSupport 8 | 9 | PlaygroundPage.current.needsIndefiniteExecution = true 10 | /*: 11 | ### Using a Global Queue 12 | iOS has some global queues, where every task eventually ends up being executed. You can use these directly. You need to use the main queue for UI updates. 13 | */ 14 | let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated) 15 | let mainQueue = DispatchQueue.main 16 | 17 | 18 | //: ### Creating your own Queue 19 | //: Creating your own queues allow you to specify a label, which is super-useful for debugging. 20 | //: You can specify whether the queue is serial (default) or concurrent (see later). 21 | //: You can also specify the QOS or priority (here be dragons) 22 | let workerQueue = DispatchQueue(label: "com.raywenderlich.worker", qos: .userInitiated) 23 | 24 | //: ### Getting the queue name 25 | //: You can't get hold of the "current queue", but you can obtain its name - useful for debugging 26 | func currentQueueName() -> String { 27 | let label = __dispatch_queue_get_label(.none) 28 | return String(cString: label) 29 | } 30 | 31 | 32 | let currentQueue = currentQueueName() 33 | print(currentQueue) 34 | 35 | 36 | //: ### Dispatching work asynchronously 37 | //: Send some work off to be done, and then continue on—don't await a result 38 | print("=== Sending asynchronously to Worker Queue ===") 39 | workerQueue.async { 40 | print("=== ASYNC:: Executing on \(currentQueueName()) ===") 41 | } 42 | print("=== Completed sending asynchronously to worker queue ===\n") 43 | 44 | 45 | 46 | //: ### Dispatching work synchronously 47 | //: Send some work off and wait for it to complete before continuing (here be more dragons) 48 | print("=== Sending SYNChronously to Worker Queue ===") 49 | workerQueue.sync { 50 | print("=== SYNC:: Executing on \(currentQueueName()) ===") 51 | } 52 | print("=== Completed sending synchronously to worker queue ===\n") 53 | 54 | 55 | 56 | //: ### Concurrent and serial queues 57 | //: Serial allows one job to be worked on at a time, concurrent multitple 58 | func doComplexWork() { 59 | sleep(1) 60 | print("\(currentQueueName()) :: Done!") 61 | } 62 | 63 | print("=== Starting Serial ===") 64 | workerQueue.async(execute: doComplexWork) 65 | workerQueue.async(execute: doComplexWork) 66 | workerQueue.async(execute: doComplexWork) 67 | workerQueue.async(execute: doComplexWork) 68 | 69 | sleep(5) 70 | 71 | let concurrentQueue = DispatchQueue(label: "com.raywenderlich.concurrent", qos: .userInitiated, attributes: .concurrent) 72 | 73 | print("\n=== Starting concurrent ===") 74 | concurrentQueue.async(execute: doComplexWork) 75 | concurrentQueue.async(execute: doComplexWork) 76 | concurrentQueue.async(execute: doComplexWork) 77 | concurrentQueue.async(execute: doComplexWork) 78 | 79 | 80 | 81 | sleep(5) 82 | 83 | PlaygroundPage.current.finishExecution() 84 | 85 | 86 | //: [➡ GCD Groups](@next) 87 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Async Operations.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ OperationQueue](@previous) 2 | /*: 3 | ## Wrapping Asynchronous Functions in [NS]Operation 4 | 5 | The approach you've seen thus far to wrapping functionality in `Operation` only works provided you can guarantee that all the work has been completed when the `main()` method returns. This is not the case if you're wrapping asynchronous functions, which return immediately, and return their result at a later point. 6 | 7 | `Operation` has support for this, but requires that you manage the state manually. The following KVO properties must now be kept up-to-date with the operation status: 8 | - `ready` 9 | - `executing` 10 | - `finished` 11 | 12 | In order to make this task easier, `AsyncOperation` is a custom subclass of `Operation` that handles the state change automatically, and in a slightly more _Swift-like_ manner. This reduces wrapping an asynchronous function to the following: 13 | 14 | 1. Subclass `AsyncOperation`. 15 | 2. Override `main()` and call your async function. 16 | 3. Change the `state` property of the `AsyncOperation` subclass to `.Finished` in the async callback. 17 | 18 | - important: 19 | Step 3 of these instructions is *extremely* important - it's how the queue responsible for running the operation can tell that it has completed. Otherwise it'll sit uncompleted for eternity. 20 | */ 21 | import UIKit 22 | 23 | 24 | /*: 25 | The subclass adds a `state` property, and ensures that the appropriate KVO notifications are sent when the value is updated. This is integral to how `NSOperationQueue` manages its operations 26 | */ 27 | class AsyncOperation: Operation { 28 | enum State: String { 29 | case Ready, Executing, Finished 30 | 31 | fileprivate var keyPath: String { 32 | return "is" + rawValue 33 | } 34 | } 35 | 36 | var state = State.Ready { 37 | willSet { 38 | willChangeValue(forKey: newValue.keyPath) 39 | willChangeValue(forKey: state.keyPath) 40 | } 41 | didSet { 42 | didChangeValue(forKey: oldValue.keyPath) 43 | didChangeValue(forKey: state.keyPath) 44 | } 45 | } 46 | } 47 | 48 | /*: 49 | Each of the state properties inherited from `Operation` are then overridden to defer to the new `state` property. 50 | 51 | The `asynchronous` property must be set to `true` to tell the system that you'll be managing the state manually. 52 | 53 | You also override `start()` and `cancel()` to wire in the new `state` property. 54 | */ 55 | extension AsyncOperation { 56 | // NSOperation Overrides 57 | override var isReady: Bool { 58 | return super.isReady && state == .Ready 59 | } 60 | 61 | override var isExecuting: Bool { 62 | return state == .Executing 63 | } 64 | 65 | override var isFinished: Bool { 66 | return state == .Finished 67 | } 68 | 69 | override var isAsynchronous: Bool { 70 | return true 71 | } 72 | 73 | override func start() { 74 | if isCancelled { 75 | state = .Finished 76 | return 77 | } 78 | main() 79 | state = .Executing 80 | } 81 | 82 | override func cancel() { 83 | state = .Finished 84 | } 85 | } 86 | 87 | 88 | 89 | /*: 90 | Wrapping an asynchronous function then becomes as simple as overriding the `main()` function, remembering to set the `state` parameter on completion: 91 | */ 92 | class ImageLoadOperation: AsyncOperation { 93 | var inputName: String? 94 | var outputImage: UIImage? 95 | 96 | override func main() { 97 | duration { 98 | simulateAsyncNetworkLoadImage(named: inputName) { 99 | [unowned self] (image) in 100 | self.outputImage = image 101 | self.state = .Finished 102 | } 103 | } 104 | } 105 | } 106 | 107 | //: This operation can then be used in the same way as any other `Operation`: 108 | let queue = OperationQueue() 109 | 110 | let imageLoad = ImageLoadOperation() 111 | imageLoad.inputName = "train_dusk.jpg" 112 | 113 | queue.addOperation(imageLoad) 114 | 115 | duration { 116 | queue.waitUntilAllOperationsAreFinished() 117 | } 118 | 119 | imageLoad.outputImage 120 | 121 | 122 | //: [➡ Operation Dependencies](@next) 123 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Operation Dependencies.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Async Dependencies](@previous) 2 | /*: 3 | ## Chaining [NS]Operations 4 | 5 | Standalone operations are useful, but the true power from `Operation` comes from when you chain them together, building up a complex workflow from small parts. 6 | 7 | In order to achieve this, you need to be able to pass the result of one operation to the next in the chain. This can be achieved using the `dependencies` property of `Operation`. 8 | 9 | In this demo, you have two operations - one the same filtering one you've been using, and the other one that simulates loading the source image over a network. 10 | 11 | - example: 12 | You can imagine that you might need to build up a chain that involves even more steps: 13 | - Retrieve source name from a data store 14 | - Download an image from a network 15 | - Decompress the image using a custom decompressor 16 | - Apply a filter to the image 17 | - Apply a second filter to the image 18 | - Display the image 19 | \ 20 | Each of these tasks could be modelled as an `Operation`, and the dependencies architecture would ensure that each operation will only begin once the appropriate data has been produced from a previous operation. 21 | 22 | This approach allows you to break down complex tasks into smaller, reusable operations which compose together nicely. It can lead to cleaner code. However, be warned that as with any asynchronous code, debugging can become more challenging. 23 | 24 | - note: 25 | More than one operation can depend on another, so you can actually build a dependency graph - you're not limited to a simple chain. The great part of this is that you don't have to manage the scheduling of any of these - the operation queue handles it all for you. 26 | 27 | */ 28 | import UIKit 29 | 30 | //: An operation that loads the file "over the network": 31 | class ImageLoadOperation: AsyncOperation { 32 | var inputName: String? 33 | var outputImage: UIImage? 34 | 35 | override func main() { 36 | simulateAsyncNetworkLoadImage(named: self.inputName) { 37 | [unowned self] (image) in 38 | self.outputImage = image 39 | self.state = .Finished 40 | } 41 | } 42 | } 43 | 44 | //: The same filtering operation you saw before. The `main()` method now attempts to find an input image in its dependencies if the `inputImage` property hasn't already been set. 45 | class TiltShiftOperation: Operation { 46 | var inputImage: UIImage? 47 | var outputImage: UIImage? 48 | 49 | override func main() { 50 | if let dependencyImageProvider = dependencies 51 | .filter({ $0 is FilterDataProvider }) 52 | .first as? FilterDataProvider, 53 | inputImage == .none { 54 | inputImage = dependencyImageProvider.outputImage 55 | } 56 | outputImage = tiltShift(image: inputImage) 57 | } 58 | } 59 | 60 | 61 | //: Rather than coding directly to concrete implementations, define a protocol that represents _"an object that can provide data to an image filter"_. This makes the code that searches dependencies far less brittle. 62 | 63 | protocol FilterDataProvider { 64 | var outputImage: UIImage? { get } 65 | } 66 | 67 | extension ImageLoadOperation: FilterDataProvider { 68 | 69 | } 70 | 71 | 72 | /*: 73 | To add a dependency to an `NSOperation` object, use the `addDependency()` method. 74 | However, it's a rare case when a custom operator can make the code easier to read. 75 | - important: 76 | Heed all the usual warnings about custom operators. This is a situation where they can offer genuine clarity, but that isn't often the case. 77 | */ 78 | 79 | precedencegroup Chainable { 80 | associativity: left 81 | } 82 | infix operator |> : Chainable 83 | extension Operation { 84 | static func |>(lhs: Operation, rhs: Operation) -> Operation { 85 | rhs.addDependency(lhs) 86 | return rhs 87 | } 88 | } 89 | 90 | 91 | //: Create the relevant operations 92 | let imageLoad = ImageLoadOperation() 93 | let filter = TiltShiftOperation() 94 | 95 | //: Set the input parameter on the image loading operation: 96 | imageLoad.inputName = "train_day.jpg" 97 | 98 | 99 | //: And set the dependency chain 100 | imageLoad |> filter 101 | 102 | //: Add both operations to the operation queue 103 | let queue = OperationQueue() 104 | duration { 105 | queue.addOperations([imageLoad, filter], waitUntilFinished: true) 106 | } 107 | 108 | 109 | filter.outputImage 110 | 111 | 112 | //: [➡ Operation in Practice](@next) 113 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Operations in Practice.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ Chaining Operations](@previous) 2 | /*: 3 | ## [NS]Operations in Practice 4 | 5 | You've seen how powerful `Operation` is, but not really seen it fix a real-world problem. 6 | 7 | This playground page demonstrates how you can use `Operation` to load and filter images for display in a table view, whilst maintaining the smooth scroll effect you expect from table views. 8 | 9 | This is a common problem, and comes from the fact that if you attempt expensive operations synchronously, you'll block the main queue (thread). Since this is used for rendering the UI, you cause your app to become unresponsive - temporarily freezing. 10 | 11 | The solution is to move data loading off into the background, which can be achieved easily with `Operation`. 12 | 13 | */ 14 | import UIKit 15 | import PlaygroundSupport 16 | 17 | let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 320, height: 720)) 18 | tableView.register(ImageCell.self, forCellReuseIdentifier: "ImageCell") 19 | PlaygroundPage.current.liveView = tableView 20 | tableView.rowHeight = 250 21 | 22 | 23 | //: `ImageProvider` is a class that is responsible for loading and processing an image. It creates the relevant operations, chains them together, pops them on a queue and then ensures that the output is passed back appropriately 24 | class ImageProvider { 25 | let queue = OperationQueue() 26 | var loadedImage: UIImage? 27 | var completion: ((UIImage?) -> ())? 28 | 29 | init(imageName: String) { 30 | let loadOp = ImageLoadOperation() 31 | let tiltShiftOp = TiltShiftOperation() 32 | let outputOp = ImageOutputOperation() 33 | 34 | loadOp.inputName = imageName 35 | outputOp.completion = { [unowned self] image in 36 | self.loadedImage = image 37 | self.completion?(image) 38 | } 39 | 40 | loadOp |> tiltShiftOp |> outputOp 41 | 42 | queue.addOperations([loadOp, tiltShiftOp, outputOp], waitUntilFinished: false) 43 | } 44 | 45 | func cancel() { 46 | queue.cancelAllOperations() 47 | } 48 | } 49 | 50 | //: `DataSource` is a class that represents the table's datasource and delegate 51 | class DataSource: NSObject { 52 | var imageNames = [String]() 53 | var imageProviders = [IndexPath : ImageProvider]() 54 | } 55 | 56 | //: Possibly the simplest implementation of `UITableViewDataSource`: 57 | extension DataSource: UITableViewDataSource { 58 | func numberOfSections(in tableView: UITableView) -> Int { 59 | return 1 60 | } 61 | 62 | func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 63 | return imageNames.count 64 | } 65 | 66 | func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 67 | return tableView.dequeueReusableCell(withIdentifier: "ImageCell", for: indexPath) 68 | } 69 | } 70 | 71 | extension DataSource: UITableViewDelegate { 72 | func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { 73 | if let cell = cell as? ImageCell { 74 | if let provider = imageProviders[indexPath] { 75 | if let image = provider.loadedImage { 76 | cell.transitionToImage(image: image) 77 | self.imageProviders.removeValue(forKey: indexPath) 78 | } else { 79 | provider.completion = { [unowned self] (image) in 80 | cell.transitionToImage(image: image) 81 | self.imageProviders.removeValue(forKey: indexPath) 82 | } 83 | } 84 | } else { 85 | let provider = ImageProvider(imageName: imageNames[indexPath.row]) 86 | provider.completion = { [unowned self] (image) in 87 | cell.transitionToImage(image: image) 88 | self.imageProviders.removeValue(forKey: indexPath) 89 | } 90 | imageProviders[indexPath] = provider 91 | } 92 | } 93 | } 94 | 95 | func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { 96 | if let cell = cell as? ImageCell { 97 | cell.transitionToImage(image: .none) 98 | } 99 | if let provider = imageProviders[indexPath] { 100 | provider.cancel() 101 | imageProviders.removeValue(forKey: indexPath) 102 | } 103 | } 104 | } 105 | 106 | extension DataSource: UITableViewDataSourcePrefetching { 107 | func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { 108 | for indexPath in indexPaths { 109 | let provider = ImageProvider(imageName: imageNames[indexPath.row]) 110 | imageProviders[indexPath] = provider 111 | } 112 | } 113 | 114 | func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) { 115 | for indexPath in indexPaths { 116 | if let provider = imageProviders[indexPath] { 117 | provider.cancel() 118 | imageProviders.removeValue(forKey: indexPath) 119 | } 120 | } 121 | } 122 | } 123 | 124 | //: Create a datasource and provide a list of images to display 125 | let ds = DataSource() 126 | ds.imageNames = ["dark_road_small.jpg", "train_day.jpg", "train_dusk.jpg", "train_night.jpg", "dark_road_small.jpg", "train_day.jpg", "train_dusk.jpg", "train_night.jpg", "dark_road_small.jpg", "train_day.jpg", "train_dusk.jpg", "train_night.jpg", "dark_road_small.jpg", "train_day.jpg", "train_dusk.jpg", "train_night.jpg"] 127 | 128 | tableView.dataSource = ds 129 | tableView.delegate = ds 130 | tableView.prefetchDataSource = ds 131 | 132 | /*: 133 | - note: 134 | This implementation for a table view is not complete, but instead meant to demonstrate how you can use `Operation` to improve the scrolling performance. 135 | 136 | [➡ Grand Central Dispatch](@next) 137 | */ 138 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016 Razeware LLC 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in 12 | * all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | * THE SOFTWARE. 21 | */ 22 | 23 | import UIKit 24 | import Accelerate 25 | 26 | extension UIImage { 27 | public func applyBlur(radius: CGFloat, maskImage: UIImage? = nil) -> UIImage? { 28 | // Check pre-conditions. 29 | if (size.width < 1 || size.height < 1) { 30 | print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") 31 | return nil 32 | } 33 | if self.cgImage == nil { 34 | print("*** error: image must be backed by a CGImage: \(self)") 35 | return nil 36 | } 37 | if maskImage != nil && maskImage!.cgImage == nil { 38 | print("*** error: maskImage must be backed by a CGImage: \(maskImage)") 39 | return nil 40 | } 41 | 42 | let __FLT_EPSILON__ = CGFloat(FLT_EPSILON) 43 | let screenScale = UIScreen.main.scale 44 | let imageRect = CGRect(origin: .zero, size: size) 45 | var effectImage = self 46 | 47 | let hasBlur = radius > __FLT_EPSILON__ 48 | 49 | if hasBlur { 50 | func createEffectBuffer(context: CGContext) -> vImage_Buffer { 51 | let data = context.data 52 | let width = vImagePixelCount(context.width) 53 | let height = vImagePixelCount(context.height) 54 | let rowBytes = context.bytesPerRow 55 | 56 | return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) 57 | } 58 | 59 | UIGraphicsBeginImageContextWithOptions(size, false, screenScale) 60 | let effectInContext = UIGraphicsGetCurrentContext()! 61 | 62 | effectInContext.scaleBy(x: 1.0, y: -1.0) 63 | effectInContext.translateBy(x: 0, y: -size.height) 64 | effectInContext.draw(self.cgImage!, in: imageRect) 65 | 66 | var effectInBuffer = createEffectBuffer(context: effectInContext) 67 | 68 | 69 | 70 | UIGraphicsBeginImageContextWithOptions(size, false, screenScale) 71 | let effectOutContext = UIGraphicsGetCurrentContext()! 72 | 73 | var effectOutBuffer = createEffectBuffer(context: effectOutContext) 74 | 75 | 76 | if hasBlur { 77 | // A description of how to compute the box kernel width from the Gaussian 78 | // radius (aka standard deviation) appears in the SVG spec: 79 | // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement 80 | // 81 | // For larger values of 's' (s >= 2.0), an approximation can be used: Three 82 | // successive box-blurs build a piece-wise quadratic convolution kernel, which 83 | // approximates the Gaussian kernel to within roughly 3%. 84 | // 85 | // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) 86 | // 87 | // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. 88 | // 89 | 90 | let inputRadius = radius * screenScale 91 | var radius = UInt32(floor(Double(inputRadius * 0.75 * sqrt(2.0 * .pi) + 0.5))) 92 | if radius % 2 != 1 { 93 | radius += 1 // force radius to be odd so that the three box-blur methodology works. 94 | } 95 | 96 | let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) 97 | 98 | vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) 99 | vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) 100 | vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) 101 | } 102 | 103 | effectImage = UIGraphicsGetImageFromCurrentImageContext()! 104 | 105 | UIGraphicsEndImageContext() 106 | UIGraphicsEndImageContext() 107 | } 108 | 109 | // Set up output context. 110 | UIGraphicsBeginImageContextWithOptions(size, false, screenScale) 111 | let outputContext = UIGraphicsGetCurrentContext() 112 | outputContext!.scaleBy(x: 1.0, y: -1.0) 113 | outputContext!.translateBy(x: 0, y: -size.height) 114 | 115 | // Draw base image. 116 | outputContext!.draw(self.cgImage!, in: imageRect) 117 | 118 | // Draw effect image. 119 | if hasBlur { 120 | outputContext!.saveGState() 121 | if let image = maskImage { 122 | let effectCGImage = effectImage.cgImage!.masking(image.cgImage!) 123 | if let effectCGImage = effectCGImage { 124 | effectImage = UIImage(cgImage: effectCGImage) 125 | } 126 | } 127 | outputContext!.draw(effectImage.cgImage!, in: imageRect) 128 | outputContext!.restoreGState() 129 | } 130 | 131 | // Output image is ready. 132 | let outputImage = UIGraphicsGetImageFromCurrentImageContext() 133 | UIGraphicsEndImageContext() 134 | 135 | return outputImage 136 | } 137 | } 138 | 139 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/Pages/Futures.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [⬅ Dispatch Barriers](@previous) 2 | 3 | /*: 4 | ## Futures 5 | 6 | GCD is a great abstraction for concurrent programming, but suffers from unnecessary 7 | complexity when chaining multiple asynchronous tasks together. This manifests itself 8 | through a so-called "pyramid-of-doom". 9 | 10 | An abstraction popular in the JavaScript community is to use a construct known as a "future" or 11 | "promise". A future is an object that represents the value that an asynchronous value will 12 | eventually resolve to. As such you can use a future as if it were a real value, and easily chain 13 | asynchronous tasks together. 14 | 15 | Futures also offer a huge advantage in error handling, through the use of a `Result` type - allowing 16 | an async operation to either resolve to a value, or an error. 17 | 18 | In this treatment of futures, you'll disover how to construct a future, without reference to error 19 | handling. This will allow you to properly understand the concepts before moving on to more complete 20 | implementations. 21 | 22 | */ 23 | 24 | import PlaygroundSupport 25 | import Foundation 26 | 27 | PlaygroundPage.current.needsIndefiniteExecution = true 28 | 29 | 30 | /*: 31 | A `Future` struct generic over the result type. Constructed with an async operation; that is a 32 | closure that accepts a completion handler as an argument. The completion handler is called once 33 | the operation is completed, and provides the result `T`. 34 | 35 | A `Future` has a `resolve()` method which actually invokes the supplied async oepration, and 36 | calls the supplied completion handler with the result. 37 | 38 | The `then()` method allows chaining of futures - taking a closure which accepts the result of the 39 | first future and a new callback. 40 | */ 41 | 42 | struct Future { 43 | typealias FutureResultHandler = (T) -> () 44 | typealias AsyncOperation = (@escaping FutureResultHandler) -> () 45 | 46 | private let asyncOperation: AsyncOperation 47 | 48 | init(asyncOperation: @escaping AsyncOperation) { 49 | self.asyncOperation = asyncOperation 50 | } 51 | 52 | func resolve(_ handler: @escaping FutureResultHandler) { 53 | asyncOperation(handler) 54 | } 55 | 56 | func then(_ next: @escaping (_ input: T, _ callback: @escaping (U) -> ()) -> ()) -> Future { 57 | return Future { (resultHandler) in 58 | self.resolve { firstResult in 59 | next(firstResult) { secondResult in 60 | resultHandler(secondResult) 61 | } 62 | } 63 | } 64 | } 65 | } 66 | 67 | 68 | let queue = DispatchQueue(label: "com.razeware.sams-queue") 69 | 70 | /*: 71 | ### Sample Async Operations 72 | */ 73 | // Data load 74 | func loadData(_ callback: @escaping ([Int]) -> ()) { 75 | queue.async { 76 | usleep(500_000) 77 | callback(Array(1...10)) 78 | } 79 | } 80 | 81 | 82 | // Image load 83 | func loadImages(_ input: [Int], callback: @escaping ([String]) -> ()) { 84 | queue.async { 85 | usleep(500_000) 86 | callback(input.map { String(repeating: "🐠" , count: $0) }) 87 | } 88 | } 89 | 90 | 91 | // Image Processing 92 | func processImages(_ input: [String], callback: @escaping ([String]) -> ()) { 93 | queue.async { 94 | usleep(500_000) 95 | callback(input.map { $0.replacingOccurrences(of: "🐠🐠🐠🐠", with: "🐙") } ) 96 | } 97 | } 98 | 99 | func secondaryProcessing(_ input: [String], callback: @escaping ([String]) -> ()) { 100 | queue.async { 101 | usleep(1_000_000) 102 | callback(input.map { return "💄" + $0 + "🎏"} ) 103 | } 104 | } 105 | 106 | /*: 107 | ### Without Futures 108 | 109 | Chaining this operations without futures results in a steady drift across the screen: the 110 | _pyramid-of-doom_. 111 | */ 112 | 113 | loadData { (data) in 114 | loadImages(data, callback: { (images) in 115 | processImages(images, callback: { (result) in 116 | secondaryProcessing(result, callback: { (output) in 117 | DispatchQueue.main.async { 118 | print("This is your processed data:") 119 | for value in output { 120 | print(value) 121 | } 122 | } 123 | }) 124 | }) 125 | }) 126 | } 127 | 128 | 129 | /*: 130 | ### With Futures 131 | 132 | A lot more readable, a fluent API clearly defining the flow of operations 133 | */ 134 | 135 | Future(asyncOperation: loadData) 136 | .then(loadImages) 137 | .then(processImages) 138 | .then(secondaryProcessing) 139 | .resolve { results in 140 | DispatchQueue.main.async { 141 | print(results) 142 | PlaygroundPage.current.finishExecution() 143 | } 144 | } 145 | 146 | 147 | /*: 148 | -note: 149 | You'll notice that this looks a lot like the procedure used at the beginning of the workshop with 150 | Operations. This is because an Operation is pretty-much the same as a future/promise. 151 | 152 | As mentioned at the top of this, a more-proper treatment of Futures would also handle errors, via 153 | a `Result` enum: 154 | */ 155 | 156 | enum Result { 157 | case success(T) 158 | case failure(E) 159 | } 160 | 161 | /*: 162 | This allows error handling to be combined at the end of the chain of futures, rather than at 163 | each indvidual step. This is much nicer error handling model. 164 | 165 | Futures/Promises are actually just a special case of something known as a *Signal*, used in 166 | Functional Reactive Programming models. Popular implementations of this model include *RxSwift* and 167 | *ReactiveCocoa*. Wheras a promise can only represent a single value, a signal represents a stream 168 | of values, over time. This is great for modelling things such as UI changes, and data changes. 169 | 170 | Signals maintain the nice fluent API of creating processing chains, and the attractive error 171 | handling model. 172 | 173 | --- 174 | Hope you enjoyed this playground introduction to concurrency on iOS. Any questions please feel free to shout at me on twitter — I'm [@iwantmyrealname](https://twitter.com/iwantmyrealname). 175 | 176 | —sam 177 | 178 | 179 | ![Razeware](razeware_64.png) 180 | 181 | © Razeware LLC, 2016 182 | */ 183 | 184 | -------------------------------------------------------------------------------- /ConcurrencyIsHard.playground/UIImage+Blur.remap: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 4 | "offset": 1204, 5 | "text": "_ ", 6 | }, 7 | { 8 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 9 | "offset": 1632, 10 | "remove": 2, 11 | "text": "cg", 12 | }, 13 | { 14 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 15 | "offset": 1837, 16 | "remove": 8, 17 | }, 18 | { 19 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 20 | "offset": 1894, 21 | "remove": 1, 22 | "text": ".z", 23 | }, 24 | { 25 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 26 | "offset": 2043, 27 | "text": "_ ", 28 | }, 29 | { 30 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 31 | "offset": 2101, 32 | "remove": 9, 33 | "text": "c", 34 | }, 35 | { 36 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 37 | "offset": 2116, 38 | "remove": 4, 39 | "text": ".d", 40 | }, 41 | { 42 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 43 | "offset": 2123, 44 | "remove": 9, 45 | }, 46 | { 47 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 48 | "offset": 2170, 49 | "remove": 9, 50 | "text": "c", 51 | }, 52 | { 53 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 54 | "offset": 2185, 55 | "remove": 4, 56 | "text": ".w", 57 | }, 58 | { 59 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 60 | "offset": 2193, 61 | "remove": 10, 62 | "text": ")", 63 | }, 64 | { 65 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 66 | "offset": 2242, 67 | "remove": 9, 68 | "text": "c", 69 | }, 70 | { 71 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 72 | "offset": 2257, 73 | "remove": 5, 74 | "text": ".he", 75 | }, 76 | { 77 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 78 | "offset": 2266, 79 | "remove": 10, 80 | "text": ")", 81 | }, 82 | { 83 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 84 | "offset": 2300, 85 | "remove": 9, 86 | "text": "c", 87 | }, 88 | { 89 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 90 | "offset": 2315, 91 | "remove": 4, 92 | "text": ".b", 93 | }, 94 | { 95 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 96 | "offset": 2329, 97 | "remove": 9, 98 | }, 99 | { 100 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 101 | "offset": 2597, 102 | "remove": 19, 103 | "text": "e", 104 | }, 105 | { 106 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 107 | "offset": 2630, 108 | "remove": 1, 109 | "text": ".scaleBy(x:", 110 | }, 111 | { 112 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 113 | "offset": 2637, 114 | "text": "y: ", 115 | }, 116 | { 117 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 118 | "offset": 2649, 119 | "remove": 3, 120 | "text": "effectInC", 121 | }, 122 | { 123 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 124 | "offset": 2658, 125 | "remove": 1, 126 | "text": ".t", 127 | }, 128 | { 129 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 130 | "offset": 2667, 131 | "remove": 20, 132 | "text": "By(x:", 133 | }, 134 | { 135 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 136 | "offset": 2691, 137 | "text": "y: ", 138 | }, 139 | { 140 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 141 | "offset": 2711, 142 | "remove": 20, 143 | "text": "e", 144 | }, 145 | { 146 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 147 | "offset": 2745, 148 | "remove": 1, 149 | "text": ".draw(in:", 150 | }, 151 | { 152 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 153 | "offset": 2758, 154 | "text": "image: ", 155 | }, 156 | { 157 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 158 | "offset": 2763, 159 | "remove": 2, 160 | "text": "cg", 161 | }, 162 | { 163 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 164 | "offset": 2770, 165 | "text": "!", 166 | }, 167 | { 168 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 169 | "offset": 4554, 170 | "text": "!", 171 | }, 172 | { 173 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 174 | "offset": 4798, 175 | "remove": 19, 176 | "text": "o", 177 | }, 178 | { 179 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 180 | "offset": 4829, 181 | "remove": 1, 182 | "text": "?.scaleBy(x:", 183 | }, 184 | { 185 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 186 | "offset": 4836, 187 | "text": "y: ", 188 | }, 189 | { 190 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 191 | "offset": 4846, 192 | "remove": 3, 193 | "text": "outputC", 194 | }, 195 | { 196 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 197 | "offset": 4855, 198 | "remove": 1, 199 | "text": "?.t", 200 | }, 201 | { 202 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 203 | "offset": 4864, 204 | "remove": 18, 205 | "text": "By(x:", 206 | }, 207 | { 208 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 209 | "offset": 4886, 210 | "text": "y: ", 211 | }, 212 | { 213 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 214 | "offset": 4933, 215 | "remove": 20, 216 | "text": "o", 217 | }, 218 | { 219 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 220 | "offset": 4965, 221 | "remove": 1, 222 | "text": "?.draw(in:", 223 | }, 224 | { 225 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 226 | "offset": 4978, 227 | "text": "image: ", 228 | }, 229 | { 230 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 231 | "offset": 4983, 232 | "remove": 2, 233 | "text": "cg", 234 | }, 235 | { 236 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 237 | "offset": 4990, 238 | "text": "!", 239 | }, 240 | { 241 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 242 | "offset": 5046, 243 | "remove": 3, 244 | "text": "outputC", 245 | }, 246 | { 247 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 248 | "offset": 5055, 249 | "remove": 1, 250 | "text": "?.s", 251 | }, 252 | { 253 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 254 | "offset": 5066, 255 | "remove": 13, 256 | }, 257 | { 258 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 259 | "offset": 5214, 260 | "remove": 23, 261 | "text": "e", 262 | }, 263 | { 264 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 265 | "offset": 5248, 266 | "remove": 2, 267 | "text": "cg", 268 | }, 269 | { 270 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 271 | "offset": 5255, 272 | "remove": 3, 273 | "text": "?.masking(i", 274 | }, 275 | { 276 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 277 | "offset": 5263, 278 | "remove": 2, 279 | "text": "cg", 280 | }, 281 | { 282 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 283 | "offset": 5270, 284 | "text": "!", 285 | }, 286 | { 287 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 288 | "offset": 5351, 289 | "remove": 2, 290 | "text": "cg", 291 | }, 292 | { 293 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 294 | "offset": 5399, 295 | "remove": 20, 296 | "text": "o", 297 | }, 298 | { 299 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 300 | "offset": 5431, 301 | "remove": 1, 302 | "text": "?.draw(in:", 303 | }, 304 | { 305 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 306 | "offset": 5444, 307 | "remove": 1, 308 | "text": "image: e", 309 | }, 310 | { 311 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 312 | "offset": 5456, 313 | "remove": 2, 314 | "text": "cg", 315 | }, 316 | { 317 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 318 | "offset": 5463, 319 | "text": "!", 320 | }, 321 | { 322 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 323 | "offset": 5471, 324 | "remove": 3, 325 | "text": "outputC", 326 | }, 327 | { 328 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 329 | "offset": 5480, 330 | "remove": 1, 331 | "text": "?.r", 332 | }, 333 | { 334 | "file": "/Users/sam/dev/razeware/talks/2016_360iDev/ConcurrencyWorkshop/ConcurrencyIsHard.playground/Sources/Graphics/UIImage+Blur.swift", 335 | "offset": 5494, 336 | "remove": 13, 337 | } 338 | ] 339 | --------------------------------------------------------------------------------