Common Utility Extensions in Swift (Utils.swift)

11 / Aug / 2015 by Abhayam Rastogi 0 comments

What is Extension:

Extensions are basically similar to an Objective-C category. Extensions are sort of methods adding in a Classe or Structure in a different flavour.

Syntax of Extension:

The syntax to create an extension is very similar to creating a type. You can write the following code in your Utils.swift class to add a UIColor extension.

extension UIColor
{
    //Fill in the blank
}

Common Extensions List:

NSData Extensions:

//MARK: NSData Extensions
extension NSData {
    
    // Convert Data to HexString mostly used in Encrypton Algos
    public var hexString: String {
        return self.toHexString()
    }
    
    func toHexString() -> String {
        let count = self.length / sizeof(UInt8)
        var bytesArray = [UInt8](count: count, repeatedValue: 0)
        self.getBytes(&bytesArray, length:count * sizeof(UInt8))
        
        var s:String = "";
        for byte in bytesArray {
            s = s + String(format:"%02X", byte)
        }
        return s;
    }   

	// Return Swift Array from NSData
    
    
    public func arrayOfBytes() -> [UInt8] {
        let count = self.length / sizeof(UInt8)
        var bytesArray = [UInt8](count: count, repeatedValue: 0)
        self.getBytes(&bytesArray, length:count * sizeof(UInt8))
        return bytesArray
    }
    
    // Return array from NSData
    class public func withBytes(bytes: [UInt8]) -> NSData {
        return NSData(bytes: bytes, length: bytes.count)
    }
}

Note: NSData has an initializer that looks takes a bytes pointer: init(bytes: UnsafeMutablePointer , length: Int).

You can read more about unsafe pointer parameters in Apple’s Interacting with C APIs

NSFileManager Extensions:

//MARK: NSFileManager Extensions

extension NSFileManager {
    class func documentsDirectory() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as! [String]
        return paths[0]
    }
    
    class func cachesDirectory() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as! [String]
        return paths[0]
    }
}

Array Extensions:

//MARK: Array Extensions
extension Array {
   
    //Array First Object
    
    func firstObject() -> T! {
        var firstItem: T!
        if !self.isEmpty {
            firstItem = self[0]
        }
        return firstItem
    }
    
    //Array Last Object
    
    func lastObject() -> T! {
        var lastItem: T!
        if !self.isEmpty {
            lastItem = self[self.count-1]
        }
        
        return lastItem
    }
    
    
    
    // Remove Object from Array similar to [ArrayObjec removeObject:(id)] in Objective-C

    mutating func removeObject(object: U) -> Bool {
        for (idx, objectToCompare) in enumerate(self) {
            if let to = objectToCompare as? U {
                if object == to {
                    self.removeAtIndex(idx)
                    return true
                }
            }
        }
        return false
    }
    
    // Check Array contains Object similar to [ArrayObjec containsObject:(id)] in Objective-C
    
    func contains(obj: T) -> Bool {
            return self.filter({$0 as? T == obj}).count > 0
        }
}

NSObject Extensions:

// Perform selector after delay in swift

extension NSObject {
    
    func callSelectorAsync(selector: Selector, object: AnyObject?, delay: NSTimeInterval) -> NSTimer {
        
        var timer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: selector, userInfo: object, repeats: false)
        return timer
    }
}

Localization String Extensions:

// localized string extension

extension  String {
    var localized: String {
        return NSLocalizedString(self, tableName:nil, bundle: NSBundle.mainBundle(), value: self, comment: "")
    }
}


// localizing String with comment

extension String{
    
    func localizedStringWithComment(comment:String)-> String{
        return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: self, comment: comment)
    }
    
}

extension String{
    
 // MARK: Remove White Spaces

    var condenseWhitespace:String{
        return  self.stringByReplacingOccurrencesOfString(" ", withString: "")
    }
}

Integer Extensions:

// MARK: Integer Extensions

//Add space before Integer
extension Int {
    func format(f: String) -> String {
        return NSString(format: "%\(f)d", self) as String
    }
}

//MARK: Double Extensions

//Add space before Double
extension Double {
    func format(f: String) -> String {
        return NSString(format: "%\(f)f", self) as String
    }
}

Source:

The Swift Programming Language: Extensions – Apple

Tag -

iOS
FOUND THIS USEFUL? SHARE IT

Leave a comment -