Apple Swift 3 beta 6中withMemoryRebound的用法 [英] Usage of withMemoryRebound with Apples Swift 3 beta 6

查看:284
本文介绍了Apple Swift 3 beta 6中withMemoryRebound的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.我想转换旧功能(在Swift 3 beta 5之前可用):

I have the following Problem. I want to convert my old function (worked until Swift 3 beta 5):

func binarytotype <T> (_ value: [UInt8], _: T.Type) -> T
{
    return value.withUnsafeBufferPointer
    {
        return UnsafePointer<T>($0.baseAddress!).pointee
    }
}

Swift 3 beta 6语法.此函数将UInt8数组转换为另一种类型,例如:

To Swift 3 beta 6 Syntax. This function converts an array of UInt8 to another type, for example:

let b: [UInt8] = [1,2,3,4,5,6,7,8]
var number: Double = binarytotype(b, Double.self)

但是现在在beta 6中这不再起作用了,我必须使用withMemoryRebound,但是我真的不知道如何使它运行.有人可以帮我吗?

But for now this does not work any more in beta 6 and I have to use withMemoryRebound but I really do not know, how to make it run. Can anybody help me?

其反向功能是:

func typetobinary <T> (_ value: T) -> [UInt8]
{
    var v: T = value
    return withUnsafePointer(to: &v)
    {
        Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>($0), count: MemoryLayout<T>.size))
    }
}

这也不再起作用.同样的问题.我的某些项目都需要两者.此反向功能称为:

This does not work any more, too. Same problem. Both are needed for some of my projects. This reverse function was called as:

var binary: [UInt8] = typetobinary(number)

推荐答案

自Xcode 8 beta 6起,指针转换变得更加冗长". 这是一个可能的解决方案:

Pointer conversions are much more "verbose" now since Xcode 8 beta 6. Here is a possible solution:

func binarytotype <T> (_ value: [UInt8], _: T.Type) -> T {
    return value.withUnsafeBufferPointer {
        UnsafeRawPointer($0.baseAddress!).load(as: T.self)
    }
}

func typetobinary<T>(_ value: T) -> [UInt8] {
    var data = [UInt8](repeating: 0, count: MemoryLayout<T>.size)
    data.withUnsafeMutableBufferPointer {
        UnsafeMutableRawPointer($0.baseAddress!).storeBytes(of: value, as: T.self)
    }
    return data
}

示例:

let d = typetobinary(UInt16(1000))
print(d) // [232, 3]
let i = binarytotype(d, UInt16.self)
print(i) // 1000

请参见 SE-0107 UnsafeRawPointer API 为了 有关新的原始指针API的详细信息.

See SE-0107 UnsafeRawPointer API for detailed information about the new raw pointer API.

这篇关于Apple Swift 3 beta 6中withMemoryRebound的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆