我正在为iOS Swift中的shapefile构建一个自定义文件打开器(一种GIS格式,与此问题无关).这些文件有一个100字节长的标题.我能够将其读入4字节数组,存储我想要的信息.我可以将这些数组转换成斯威夫特类型Data和NSData,并有转化他们(像一些其他选项Base64EncodedString).但我无法将这些原料阵列或数据或任何的格式转换成有用的属性等Double,Int和String.
import Foundation
struct ShapeReader {
var shapeFile = FileHandle(forReadingAtPath: "/Users/christopherjlowrie/Documents/Shapes/SF_Neighborhoods/Planning_Zones.shp")
var fileHeader: String{
let header = shapeFile?.readData(ofLength: 100)
let headerStream = InputStream(data: header!)
headerStream.open()
var buffer = [UInt8](repeating: 0, count: 4)
while (headerStream.hasBytesAvailable){
headerStream.read(&buffer, maxLength: buffer.count)
print(buffer)
let x = Data(buffer)
print(x)
}
return "A"
}
}
Run Code Online (Sandbox Code Playgroud)
这当前只返回A,因为测试原因我返回一个字符串
我怎么能打开文件,并阅读他们的原始字节分为不同的类型(Doubles,Ints,Strings)的斯威夫特?
Leo*_*bus 13
你可以这样做:
要从String,Int或Double转换为数据:
Xcode 9•Swift 4 //对于旧的Swift 3语法,请单击此处
extension StringProtocol {
var data: Data { .init(utf8) }
}
Run Code Online (Sandbox Code Playgroud)
要从Data转换回String,Int或Double:
extension Numeric {
var data: Data {
var source = self
// This will return 1 byte for 8-bit, 2 bytes for 16-bit, 4 bytes for 32-bit and 8 bytes for 64-bit binary integers. For floating point types it will return 4 bytes for single-precision, 8 bytes for double-precision and 16 bytes for extended precision.
return .init(bytes: &source, count: MemoryLayout<Self>.size)
}
}
Run Code Online (Sandbox Code Playgroud)
游乐场测试
extension DataProtocol {
var string: String? { String(bytes: self, encoding: .utf8) }
}
Run Code Online (Sandbox Code Playgroud)
extension Numeric {
init<D: DataProtocol>(_ data: D) {
var value: Self = .zero
let size = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} )
assert(size == MemoryLayout.size(ofValue: value))
self = value
}
}
Run Code Online (Sandbox Code Playgroud)
extension DataProtocol {
func value<N: Numeric>() -> N { .init(self) }
}
Run Code Online (Sandbox Code Playgroud)
let value = 12.34 // implicit Double 12.34
let data = value.data // double data - 8 bytes
let double = Double(data) // implicit Double 12.34
let double1: Double = .init(data) // explicit Double 12.34
let double2: Double = data.value() // explicit Double 12.34
let double3 = data.value() as Double // casting to Double 12.34
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2614 次 |
| 最近记录: |