Skip to content

Instantly share code, notes, and snippets.

@sinoru
Last active April 12, 2019 02:21
Show Gist options
  • Select an option

  • Save sinoru/41368d5c1121438728cec2cf3a1c1f01 to your computer and use it in GitHub Desktop.

Select an option

Save sinoru/41368d5c1121438728cec2cf3a1c1f01 to your computer and use it in GitHub Desktop.
DispatchQueue Perform Safely
//
// DispatchQueue.swift
//
// Created by Jaehong Kang on 12/04/2019.
// Copyright © 2019 Jaehong Kang. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
extension DispatchQueue {
private static let isCurrentQueueKey = DispatchSpecificKey<Bool>()
open func perform<T>(execute closure: () throws -> T) rethrows -> T {
self.setSpecific(key: DispatchQueue.isCurrentQueueKey, value: true)
defer {
self.setSpecific(key: DispatchQueue.isCurrentQueueKey, value: nil)
}
guard DispatchQueue.getSpecific(key: DispatchQueue.isCurrentQueueKey) == true else {
return try self.sync(execute: closure)
}
return try closure()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment