본문 바로가기

아이폰

swift로 Data 처리 하는 Extension 모음

ble 통신할때 data를 변환할 일이 많아서 정리 해놓음

 

import Foundation


extension NSData {

    var uint8: UInt8 {

        get {

            var number: UInt8 = 0

            self.getBytes(&number, length: MemoryLayout<UInt8>.size)

            return number

        }

    }

}


extension NSData {

    var uint16: UInt16 {

        get {

            var number: UInt16 = 0

            self.getBytes(&number, length: MemoryLayout<UInt16>.size )

            return number

        }

    }

}


extension NSData {

    var uint32: UInt32 {

        get {

            var number: UInt32 = 0

            self.getBytes(&number, length:MemoryLayout<UInt32>.size  )

            return number

        }

    }

}


extension NSData {

    var uuid: NSUUID? {

        get {

            var bytes = [UInt8](repeating: 0, count: self.length)

            self.getBytes(&bytes, length: self.length * MemoryLayout<UInt8>.size)

            return NSUUID(uuidBytes: bytes)

        }

    }

}


extension NSData {

    var stringASCII: String? {

        get {

            return NSString(data: self as Data, encoding: String.Encoding.ascii.rawValue) as String?

        }

    }

}


extension NSData {

    var stringUTF8: String? {

        get {

            return NSString(data: self as Data, encoding: String.Encoding.utf8.rawValue) as String?

        }

    }

}


extension Int {

    var data: NSData {

        var int = self

        return NSData(bytes: &int, length: MemoryLayout<Int>.size)

    }

}


extension UInt8 {

    var data: NSData {

        var int = self

        return NSData(bytes: &int, length: MemoryLayout<UInt8>.size)

    }

}


extension UInt16 {

    var data: NSData {

        var int = self

        return NSData(bytes: &int, length: MemoryLayout<UInt16>.size)

    }

}


extension UInt32 {

    var data: NSData {

        var int = self

        return NSData(bytes: &int, length: MemoryLayout<UInt32>.size)

    }

}


extension NSUUID {

    var data: NSData {

        var uuid = [UInt8](repeating: 0, count: 16)

        self.getBytes(&uuid)

        return NSData(bytes: &uuid, length: 16)

    }

}


extension String {

    var dataUTF8: NSData? {

        return self.data(using: String.Encoding.utf8) as NSData?

    }

}


extension NSString {

    var dataASCII: NSData? {

        return self.data(using: String.Encoding.ascii.rawValue) as NSData?

    }

}



'아이폰' 카테고리의 다른 글

cocoapod이 갑자기 안될때 해결책  (0) 2017.07.21
webview cookie 저장 및 불러오기  (0) 2017.05.01
swift로 Data 처리 하는 Extension 모음  (0) 2017.03.01
wkwebkit(1)  (0) 2017.02.11
swift viewWillDisappear  (0) 2016.10.27
backbutton 타이틀 없애기  (0) 2016.10.18