-
-
Save huguesbr/b2a316a4753093015a27 to your computer and use it in GitHub Desktop.
Convert to and from NSData for common Swift types. Includes Eddystone URL conversion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSDataExtensions.swift | |
// MAPO | |
// | |
// Created by Hugues Bernet-Rollande on 21/3/16. | |
// Copyright © 2016 WB Technologies. All rights reserved. | |
// | |
import Foundation | |
// https://gist.github.com/tannernelson/73d0923efdee50e6c38f | |
extension NSData { | |
var uint8: UInt8 { | |
get { | |
var number: UInt8 = 0 | |
self.getBytes(&number, length: sizeof(UInt8)) | |
return number | |
} | |
} | |
} | |
extension NSData { | |
var uint16: UInt16 { | |
get { | |
var number: UInt16 = 0 | |
self.getBytes(&number, length: sizeof(UInt16)) | |
return number | |
} | |
} | |
} | |
extension NSData { | |
var uint32: UInt32 { | |
get { | |
var number: UInt32 = 0 | |
self.getBytes(&number, length: sizeof(UInt32)) | |
return number | |
} | |
} | |
} | |
extension NSData { | |
var uuid: NSUUID? { | |
get { | |
var bytes = [UInt8](count: self.length, repeatedValue: 0) | |
self.getBytes(&bytes, length: self.length * sizeof(UInt8)) | |
return NSUUID(UUIDBytes: bytes) | |
} | |
} | |
} | |
extension NSData { | |
var stringASCII: String? { | |
get { | |
return NSString(data: self, encoding: NSASCIIStringEncoding) as String? | |
} | |
} | |
} | |
extension NSData { | |
var stringUTF8: String? { | |
get { | |
return NSString(data: self, encoding: NSUTF8StringEncoding) as String? | |
} | |
} | |
} | |
extension Int { | |
var data: NSData { | |
var int = self | |
return NSData(bytes: &int, length: sizeof(Int)) | |
} | |
} | |
extension UInt8 { | |
var data: NSData { | |
var int = self | |
return NSData(bytes: &int, length: sizeof(UInt8)) | |
} | |
} | |
extension UInt16 { | |
var data: NSData { | |
var int = self | |
return NSData(bytes: &int, length: sizeof(UInt16)) | |
} | |
} | |
extension UInt32 { | |
var data: NSData { | |
var int = self | |
return NSData(bytes: &int, length: sizeof(UInt32)) | |
} | |
} | |
extension NSUUID { | |
var data: NSData { | |
var uuid = [UInt8](count: 16, repeatedValue: 0) | |
self.getUUIDBytes(&uuid) | |
return NSData(bytes: &uuid, length: 16) | |
} | |
} | |
extension String { | |
var dataUTF8: NSData? { | |
return self.dataUsingEncoding(NSUTF8StringEncoding) | |
} | |
} | |
extension NSString { | |
var dataASCII: NSData? { | |
return self.dataUsingEncoding(NSASCIIStringEncoding) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
String
andNSData
by optionals.NSData
extension in on different extension (allowing cherry picking)string
->stringUTF8
,data
->dataUTF8
stringASCII
anddataASCII