美文网首页
swift 2 -> swift 3

swift 2 -> swift 3

作者: ping_oO | 来源:发表于2016-07-08 17:59 被阅读39次

    data.bytes
    <pre><code>
    extension Data {
    <p>
    init<T>(fromArray values: [T]) {
    <p>
    var values = values self.init(buffer: UnsafeBufferPointer(start: &values, count: values.count))
    <p> }
    <p>
    func toArray<T>(type: T.Type) -> [T] {
    <p>
    return self.withUnsafeBytes {
    <p>
    [T] (UnsafeBufferPointer(start: $0, count: self.count/sizeof(T)))
    <p> }
    <p> }
    <p>}
    </pre></code>
    <pre><code>
    Example:
    <p>let input: [Int16] = [1, Int16.max, Int16.min]
    <p>let data = Data(fromArray: input)print(data) // <0100ff7f 0080>
    <p>let roundtrip = data.toArray(type: Int16.self)print(roundtrip) // [1, 32767, -32768]
    </pre></code>

    http://stackoverflow.com/questions/38023838/round-trip-swift-number-types-to-from-data

    data.getBytes
    <pre><code>
    For NSData:
    <p>var values = [UInt8] (repeating:0, count:data!.length)data.getBytes(&values, length: data!.length)
    <p>
    <p>
    For Data:
    <p>var values = [UInt8] (repeating:0, count:data!.count)data.copyBytes(to: &values, count: data!.count)
    </pre></code>

    相关文章

      网友评论

          本文标题:swift 2 -> swift 3

          本文链接:https://www.haomeiwen.com/subject/uolrjttx.html