-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathUtilities.swift
More file actions
92 lines (74 loc) · 2.48 KB
/
Utilities.swift
File metadata and controls
92 lines (74 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//
// Utilities.swift
// Moody
//
// Created by Florian on 08/05/15.
// Copyright (c) 2015 objc.io. All rights reserved.
//
import Foundation
extension Sequence {
/// Similar to
/// ```
/// func forEach(@noescape body: (Self.Generator.Element) -> ())
/// ```
/// but calls the completion block once all blocks have called their completion block. If some of the calls to the block do not call their completion blocks that will result in data leaking.
func asyncForEach(completion: @escaping () -> (), block: (Iterator.Element, @escaping () -> ()) -> ()) {
let group = DispatchGroup()
let innerCompletion = { group.leave() }
for x in self {
group.enter()
block(x, innerCompletion)
}
group.notify(queue: DispatchQueue.main, execute: completion)
}
func all(_ condition: (Iterator.Element) -> Bool) -> Bool {
for x in self where !condition(x) {
return false
}
return true
}
func some(_ condition: (Iterator.Element) -> Bool) -> Bool {
for x in self where condition(x) {
return true
}
return false
}
}
extension Sequence where Iterator.Element: AnyObject {
public func containsObjectIdentical(to object: AnyObject) -> Bool {
return contains { $0 === object }
}
}
extension Array {
var decomposed: (Iterator.Element, [Iterator.Element])? {
guard let x = first else { return nil }
return (x, Array(self[1..<count]))
}
func sliced(size: Int) -> [[Iterator.Element]] {
var result: [[Iterator.Element]] = []
for idx in stride(from: startIndex, to: endIndex, by: size) {
let end = Swift.min(idx + size, endIndex)
result.append(Array(self[idx..<end]))
}
return result
}
}
extension URL {
static var temporary: URL {
return URL(fileURLWithPath:NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(UUID().uuidString)
}
static var documents: URL {
return try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
}
}
extension String {
public func removingCharacters(in set: CharacterSet) -> String {
var chars = characters
for idx in chars.indices.reversed() {
if set.contains(String(chars[idx]).unicodeScalars.first!) {
chars.remove(at: idx)
}
}
return String(chars)
}
}