使用NSMutableData
,我可以创建一个Int's
或Float
的数组,并将其存储到磁盘。
protocol BinaryConvertible
{
init()
}
extension Int : BinaryConvertible {}
struct Storage<T: BinaryConvertible>
{
let data = NSMutableData()
func append(value: T)
{
var input = value
data.append(&input, length: sizeof(T))
}
func extract(index: Int) -> T
{
var output = T()
let range = NSRange(location: index * sizeof(T), length: sizeof(T))
data.getBytes(&output, range: range)
return output
}
}
Swift 3有一个新的Data
类型,它使用了NSData
。与String
和NSString
一样。我无法弄清楚如何添加例如Double
使用新方法。
追加函数现在需要UnsafePointer<UInt8>
,但是如何从Double
或任何随机结构中创建这个?
答案 0 :(得分:10)
使用指针是我在Swift中最不喜欢的事情之一,但它也提供了良好的学习体验。这对我有用:
struct Storage<T: BinaryConvertible>
{
var data = Data()
mutating func append(value: T)
{
var input = value
let buffer = UnsafeBufferPointer(start: &input, count: 1)
self.data.append(buffer)
}
func extract(index: Int) -> T
{
let startIndex = index * sizeof(T)
let endIndex = startIndex + sizeof(T)
var output = T()
let buffer = UnsafeMutableBufferPointer(start: &output, count: 1)
let _ = self.data.copyBytes(to: buffer, from: startIndex..<endIndex)
return output
}
}
var s = Storage<Double>()
s.append(value: M_PI)
s.append(value: 42)
s.append(value: 100)
print(s.extract(index: 0))
print(s.extract(index: 1))
print(s.extract(index: 2))
答案 1 :(得分:2)
我喜欢使用+或+ =
<div id="page">
<div id="first-box">
</div>
<div id="second-box">
this is second box
</div>
</div>
样品
public protocol DataConvertible {
static func + (lhs: Data, rhs: Self) -> Data
static func += (lhs: inout Data, rhs: Self)
}
extension DataConvertible {
public static func + (lhs: Data, rhs: Self) -> Data {
var value = rhs
let data = Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
return lhs + data
}
public static func += (lhs: inout Data, rhs: Self) {
lhs = lhs + rhs
}
}
extension UInt8 : DataConvertible { }
extension UInt16 : DataConvertible { }
extension UInt32 : DataConvertible { }
extension Int : DataConvertible { }
extension Float : DataConvertible { }
extension Double : DataConvertible { }
extension String : DataConvertible {
public static func + (lhs: Data, rhs: String) -> Data {
guard let data = rhs.data(using: .utf8) else { return lhs}
return lhs + data
}
}
extension Data : DataConvertible {
public static func + (lhs: Data, rhs: Data) -> Data {
var data = Data()
data.append(lhs)
data.append(rhs)
return data
}
}