Skip to content

Instantly share code, notes, and snippets.

@huguesbr
Forked from tanner0101/NSDataExtensions.swift
Last active July 18, 2019 08:10
Show Gist options
  • Save huguesbr/b2a316a4753093015a27 to your computer and use it in GitHub Desktop.
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.
//
// 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)
}
}
@huguesbr
Copy link
Author

  • Removing (no usage for me) URL related conversion.
  • Replacing empty String and NSData by optionals.
  • Splitting each NSData extension in on different extension (allowing cherry picking)
  • Rename string -> stringUTF8, data -> dataUTF8
  • Adding stringASCII and dataASCII

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment