Helpers.swift 6.79 KB
Newer Older
Aral Balkan's avatar
Aral Balkan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//
//  File.swift
//  Heartbeat
//
//  Created by Aral Balkan on 25/09/2014.
//  Copyright (c) 2014 ind.ie. All rights reserved.
//

import Foundation

//
// Helpers
//

15 16 17 18 19 20
//
// Accessibility
//

func makeAccessibilityAnnouncement(message:String)
{
21 22 23 24
    //
    // Note: Documentation on NSAccessibilityAnnouncementRequestedNotification is wrong. Correct usage, via NSAccessibility.h: “This notification should be posted for the application element.”
    // (Also see http://lists.apple.com/archives/accessibility-dev/2013/Jul/msg00027.html and rdar://14543376 )
    //
25
    NSAccessibilityPostNotificationWithUserInfo(NSApp.mainWindow, NSAccessibilityAnnouncementRequestedNotification, [NSAccessibilityAnnouncementKey: message, NSAccessibilityPriorityKey: NSAccessibilityPriorityLevel.High.rawValue])
26 27
}

28

29

30
//
31 32 33 34 35 36
//  General delay method that uses Grand Central Dispatch to execute a
//  block after a specified number of seconds has elapsed. A cancellable block
//  is returned, that you can cancel by calling and passing true for the cancel parameter.
//
//  Based on CancelBlocks by Evgenii Rtishchev (https://github.com/katleta3000/CancelBlocks)
//  and http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift
37 38
//

39
typealias dispatch_cancellable_block_t = (cancel:Bool) -> (Void)
40

41
func delay(delay:Double, block:dispatch_block_t?) -> dispatch_cancellable_block_t?
Aral Balkan's avatar
Aral Balkan committed
42
{
43
    
44 45 46 47 48 49 50
    if (block == nil)
    {
        return nil
    }
    
    if delay < 0.0
    {
51 52
        // Special case. If delay is negative, run the closure on the same stack frame.
        // If you want to run the closure on the next stack frame, pass 0.0.
53 54
        block!()
        return nil
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
    var originalBlock:dispatch_block_t? = block!
    var cancellableBlock:dispatch_cancellable_block_t? = nil
    var delayBlock:dispatch_cancellable_block_t =
    {
        (cancel:Bool) -> Void in
        
        if ((!cancel) && (originalBlock != nil))
        {
            dispatch_async(dispatch_get_main_queue(), originalBlock!)
        }
        cancellableBlock = nil
        originalBlock = nil
    }
    cancellableBlock = delayBlock
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue())
    {
        () -> Void in
        
        if (cancellableBlock != nil)
        {
            cancellableBlock!(cancel: false)
        }
    }
    return cancellableBlock
Aral Balkan's avatar
Aral Balkan committed
81
}
82

83 84 85 86 87 88 89 90 91 92 93 94 95
func dispatch_cancel_block_t(block:dispatch_cancellable_block_t?)
{
    if (block != nil)
    {
        block!(cancel: true)
    }
}


//
// Other
//

96

97
//
98
// Allows graceful overriding of any NSResponder subclass’s initialisation
99 100
// using a common initialiser.
//
101
extension NSResponder {
102 103 104 105 106
    enum InitMethod {
        case Default
        case Coder(NSCoder)
    }
}
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

//
// Coverted to Swift from Cameron Lowell Palmer’s Obj-C category
// (http://stackoverflow.com/a/23606211/253485)
//
extension String {
    
    func stringByStrippingCharactersInSet(set:NSCharacterSet) -> String
    {
        return (self.componentsSeparatedByCharactersInSet(set) as NSArray).componentsJoinedByString("")
    }
    
    func stringByCollapsingWhitespace() -> String
    {
        var components:NSArray = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        let predicate = NSPredicate(format: "self <> ''", argumentArray: nil)
        components = components.filteredArrayUsingPredicate(predicate)
        
        return components.componentsJoinedByString(" ")
    }
}

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
//
// A usable String interface for common actions, courtesy of 
// http://stackoverflow.com/a/25152652/253485
//

extension String {
    
    // MARK: - substring
    func substringToIndex(index:Int) -> String {
        return self.substringToIndex(advance(self.startIndex, index))
    }
    func substringFromIndex(index:Int) -> String {
        return self.substringFromIndex(advance(self.startIndex, index))
    }
    func substringWithRange(range:Range<Int>) -> String {
        let start = advance(self.startIndex, range.startIndex)
        let end = advance(self.startIndex, range.endIndex)
        return self.substringWithRange(start..<end)
    }
    
    subscript(index:Int) -> Character{
        return self[advance(self.startIndex, index)]
    }
    subscript(range:Range<Int>) -> String {
        let start = advance(self.startIndex, range.startIndex)
        let end = advance(self.startIndex, range.endIndex)
        return self[start..<end]
    }
    
    
    // MARK: - replace
    func replaceCharactersInRange(range:Range<Int>, withString: String!) -> String {
        var result:NSMutableString = NSMutableString(string: self)
        result.replaceCharactersInRange(NSRange(range), withString: withString)
163
        return result as String
164
    }
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
}

// 
// Thanks to http://sketchytech.blogspot.co.uk/2014/08/pure-swift-stringbyreplacingoccurrences.html
//
extension String {
    func rangesOfString(findStr:String) -> [Range<String.Index>] {
        var arr = [Range<String.Index>]()
        var startInd = self.startIndex
        var i = 0
        // test first of all whether the string is likely to appear at all
        if contains(self, first(findStr)!) {
            startInd = find(self,first(findStr)!)!
        }
        else {
            return arr
        }
        // set starting point for search based on the finding of the first character
        i = distance(self.startIndex, startInd)
184 185 186 187
        while i<=count(self)-count(findStr) {
            if self[advance(self.startIndex, i)..<advance(self.startIndex, i+count(findStr))] == findStr {
                arr.append(Range(start:advance(self.startIndex, i),end:advance(self.startIndex, i+count(findStr))))
                i = i+count(findStr)
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
            }
            i++
        }
        return arr
    } // try further optimization by repeating the initial act of finding first character after each found string
    
    func stringByReplacingOccurrencesOfString(string:String, replacement:String) -> String {
        
        // get ranges first using rangesOfString: method, then glue together the string using ranges of existing string and old string
        
        let ranges = self.rangesOfString(string)
        // if the string isn't found return unchanged string
        if ranges.isEmpty {
            return self
        }
        
        var newString = ""
        var startInd = self.startIndex
        for r in ranges {
            
            newString += self[startInd..<minElement(r)]
            newString += replacement
            
            if maxElement(r) < self.endIndex {
                startInd = advance(maxElement(r),1)
            }
        }
        
        // add the last part of the string after the final find
        if maxElement(ranges.last!) < self.endIndex {
            newString += self[advance(maxElement(ranges.last!),1)..<self.endIndex]
        }
        
        return newString
    }
}