{"id":25435,"date":"2015-08-11T22:12:31","date_gmt":"2015-08-11T16:42:31","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=25435"},"modified":"2015-08-26T12:48:23","modified_gmt":"2015-08-26T07:18:23","slug":"common-utility-extensions-in-swift-utils-swift","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/common-utility-extensions-in-swift-utils-swift\/","title":{"rendered":"Common Utility Extensions in Swift (Utils.swift)"},"content":{"rendered":"<h1>What is Extension:<\/h1>\n<p>Extensions are basically similar to an Objective-C category. Extensions are sort of methods adding in a Classe or Structure in a different flavour.<\/p>\n<h1>Syntax of Extension:<\/h1>\n<p>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 <b>UIColor<\/b>\u00a0extension.<\/p>\n<div>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>extension <span style=\"color: orange;\">UIColor<\/span>\r\n{\r\n    \/\/Fill in the blank\r\n}<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h1>Common Extensions List:<\/h1>\n<h3>NSData\u00a0Extensions:<\/h3>\n<div>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>\/\/MARK: NSData Extensions\r\nextension <span style=\"color: orange;\">NSData<\/span> {\r\n    \r\n    \/\/ Convert Data to HexString mostly used in Encrypton Algos\r\n    public var hexString: String {\r\n        return self.toHexString()\r\n    }\r\n    \r\n    func toHexString() -&gt; String {\r\n        let count = self.length \/ sizeof(UInt8)\r\n        var bytesArray = [UInt8](count: count, repeatedValue: 0)\r\n        self.getBytes(&amp;bytesArray, length:count * sizeof(UInt8))\r\n        \r\n        var s:String = \"\";\r\n        for byte in bytesArray {\r\n            s = s + String(format:\"%02X\", byte)\r\n        }\r\n        return s;\r\n    }   \r\n\r\n\t\/\/ Return Swift Array from NSData\r\n    \r\n    \r\n    public func arrayOfBytes() -&gt; [UInt8] {\r\n        let count = self.length \/ sizeof(UInt8)\r\n        var bytesArray = [UInt8](count: count, repeatedValue: 0)\r\n        self.getBytes(&amp;bytesArray, length:count * sizeof(UInt8))\r\n        return bytesArray\r\n    }\r\n    \r\n    \/\/ Return array from NSData\r\n    class public func withBytes(bytes: [UInt8]) -&gt; NSData {\r\n        return NSData(bytes: bytes, length: bytes.count)\r\n    }\r\n}<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p><b>Note:<\/b> NSData has an initializer that looks takes a bytes pointer: init(bytes: UnsafeMutablePointer , length: Int).<\/p>\n<p>You can read more about unsafe pointer parameters in Apple&#8217;s Interacting with C APIs<\/p>\n<h3>NSFileManager\u00a0Extensions:<\/h3>\n<div>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>\/\/MARK: NSFileManager Extensions\r\n\r\nextension <span style=\"color: orange;\">NSFileManager<\/span> {\r\n    class func documentsDirectory() -&gt; String {\r\n        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as! [String]\r\n        return paths[0]\r\n    }\r\n    \r\n    class func cachesDirectory() -&gt; String {\r\n        var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as! [String]\r\n        return paths[0]\r\n    }\r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<div>\n<h3>Array Extensions:<\/h3>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>\/\/MARK: Array Extensions\r\nextension <span style=\"color: orange;\">Array<\/span> {\r\n   \r\n    \/\/Array First Object\r\n    \r\n    func firstObject() -&gt; T! {\r\n        var firstItem: T!\r\n        if !self.isEmpty {\r\n            firstItem = self[0]\r\n        }\r\n        return firstItem\r\n    }\r\n    \r\n    \/\/Array Last Object\r\n    \r\n    func lastObject() -&gt; T! {\r\n        var lastItem: T!\r\n        if !self.isEmpty {\r\n            lastItem = self[self.count-1]\r\n        }\r\n        \r\n        return lastItem\r\n    }\r\n    \r\n    \r\n    \r\n    \/\/ Remove Object from Array similar to [ArrayObjec removeObject:(id)] in Objective-C\r\n\r\n    mutating func removeObject(object: U) -&gt; Bool {\r\n        for (idx, objectToCompare) in enumerate(self) {\r\n            if let to = objectToCompare as? U {\r\n                if object == to {\r\n                    self.removeAtIndex(idx)\r\n                    return true\r\n                }\r\n            }\r\n        }\r\n        return false\r\n    }\r\n    \r\n    \/\/ Check Array contains Object similar to [ArrayObjec containsObject:(id)] in Objective-C\r\n    \r\n    func contains(obj: T) -&gt; Bool {\r\n            return self.filter({$0 as? T == obj}).count &gt; 0\r\n        }\r\n}\r\n\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h3>NSObject Extensions:<\/h3>\n<div>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>\/\/ Perform selector after delay in swift\r\n\r\nextension <span style=\"color: orange;\">NSObject<\/span> {\r\n    \r\n    func callSelectorAsync(selector: Selector, object: AnyObject?, delay: NSTimeInterval) -&gt; NSTimer {\r\n        \r\n        var timer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: selector, userInfo: object, repeats: false)\r\n        return timer\r\n    }\r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h3>Localization String Extensions:<\/h3>\n<div>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>\/\/ localized string extension\r\n\r\nextension  <span style=\"color: orange;\">String<\/span> {\r\n    var localized: String {\r\n        return NSLocalizedString(self, tableName:nil, bundle: NSBundle.mainBundle(), value: self, comment: \"\")\r\n    }\r\n}\r\n\r\n\r\n\/\/ localizing String with comment\r\n\r\nextension <span style=\"color: orange;\">String<\/span>{\r\n    \r\n    func localizedStringWithComment(comment:String)-&gt; String{\r\n        return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: self, comment: comment)\r\n    }\r\n    \r\n}\r\n\r\nextension <span style=\"color: orange;\">String<\/span>{\r\n    \r\n \/\/ MARK: Remove White Spaces\r\n\r\n    var condenseWhitespace:String{\r\n        return  self.stringByReplacingOccurrencesOfString(\" \", withString: \"\")\r\n    }\r\n}<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h3>Integer Extensions:<\/h3>\n<div>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>\/\/ MARK: Integer Extensions\r\n\r\n\/\/Add space before Integer\r\nextension <span style=\"color: orange;\">Int<\/span> {\r\n    func format(f: String) -&gt; String {\r\n        return NSString(format: \"%\\(f)d\", self) as String\r\n    }\r\n}\r\n\r\n\/\/MARK: Double Extensions\r\n\r\n\/\/Add space before Double\r\nextension <span style=\"color: orange;\">Double<\/span> {\r\n    func format(f: String) -&gt; String {\r\n        return NSString(format: \"%\\(f)f\", self) as String\r\n    }\r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h1>Source:<\/h1>\n<h3 class=\"r\"><a href=\"https:\/\/developer.apple.com\/library\/ios\/documentation\/Swift\/Conceptual\/Swift_Programming_Language\/Extensions.html\">The Swift Programming Language: Extensions &#8211; Apple<\/a><\/h3>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":169,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":12},"categories":[1400,1],"tags":[4848],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/25435"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/169"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=25435"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/25435\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=25435"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=25435"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=25435"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}