Skip to content

Instantly share code, notes, and snippets.

@PaulEhrhardt
Forked from huguesbr/NSDataExtensions.swift
Created July 18, 2019 08:10
Show Gist options
  • Save PaulEhrhardt/56952abf90643f3a0605bc38ac33d87a to your computer and use it in GitHub Desktop.
Save PaulEhrhardt/56952abf90643f3a0605bc38ac33d87a 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment