Helpers.swift 5.5 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
//
// Other
//

33

Aral Balkan's avatar
Aral Balkan committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47
func delay(delay:Double, closure:()->())
{
    //
    // Run the passed closure after a given number of seconds.
    //
    // Courtesy: http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift
    //
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}
48

49

50
//
51
// Allows graceful overriding of any NSResponder subclass’s initialisation
52 53
// using a common initialiser.
//
54
extension NSResponder {
55 56 57 58 59
    enum InitMethod {
        case Default
        case Coder(NSCoder)
    }
}
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

//
// 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(" ")
    }
}

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
//
// 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)
        return result
    }
118 119 120 121 122 123 124 125 126 127 128 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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
}

// 
// 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)
        while i<=countElements(self)-countElements(findStr) {
            if self[advance(self.startIndex, i)..<advance(self.startIndex, i+countElements(findStr))] == findStr {
                arr.append(Range(start:advance(self.startIndex, i),end:advance(self.startIndex, i+countElements(findStr))))
                i = i+countElements(findStr)
            }
            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
    }
}