是否可以将 String 转换为 simd_float4x4 ? ( iOS 12 )
is it possible convert String to simd_float4x4 ? ( iOS 12 )
是否可以从字符串构造 simd_float4x4,例如:我有一个存储 simd_float4x4.debugdescription 值的字符串?
这是 simd_float4x4
的 extension
,它添加了一个 failable init
,它接受调试描述并创建 simd_float4x4
.这是一个 failable init
因为字符串可能格式错误。
import simd
extension simd_float4x4 {
init?(_ string: String) {
let prefix = "simd_float4x4"
guard string.hasPrefix(prefix) else { return nil }
let csv = string.dropFirst(prefix.count).components(separatedBy: ",")
let filtered = csv.map { [=10=].filter { Array("-01234567890.").contains([=10=]) } }
let floats = filtered.compactMap(Float.init)
guard floats.count == 16 else { return nil }
let f0 = float4(Array(floats[0...3]))
let f1 = float4(Array(floats[4...7]))
let f2 = float4(Array(floats[8...11]))
let f3 = float4(Array(floats[12...15]))
self = simd_float4x4(f0, f1, f2, f3)
}
}
测试
let col0 = float4(0.1, 0.2, 0.3, 0.4)
let col1 = float4(1.1, 1.2, 1.3, 1.4)
let col2 = float4(2.1, 2.2, 2.3, 2.4)
let col3 = float4(-3.1, -3.2, -3.3, -3.4)
var x = simd_float4x4(col0, col1, col2, col3)
print(x)
let xDesc = x.debugDescription
if let y = simd_float4x4(xDesc) {
print(y)
}
输出
simd_float4x4([[0.1, 0.2, 0.3, 0.4)], [1.1, 1.2, 1.3, 1.4)], [2.1, 2.2, 2.3, 2.4)], [-3.1, -3.2, -3.3, -3.4)]])
simd_float4x4([[0.1, 0.2, 0.3, 0.4)], [1.1, 1.2, 1.3, 1.4)], [2.1, 2.2, 2.3, 2.4)], [-3.1, -3.2, -3.3, -3.4)]])
是否可以从字符串构造 simd_float4x4,例如:我有一个存储 simd_float4x4.debugdescription 值的字符串?
这是 simd_float4x4
的 extension
,它添加了一个 failable init
,它接受调试描述并创建 simd_float4x4
.这是一个 failable init
因为字符串可能格式错误。
import simd
extension simd_float4x4 {
init?(_ string: String) {
let prefix = "simd_float4x4"
guard string.hasPrefix(prefix) else { return nil }
let csv = string.dropFirst(prefix.count).components(separatedBy: ",")
let filtered = csv.map { [=10=].filter { Array("-01234567890.").contains([=10=]) } }
let floats = filtered.compactMap(Float.init)
guard floats.count == 16 else { return nil }
let f0 = float4(Array(floats[0...3]))
let f1 = float4(Array(floats[4...7]))
let f2 = float4(Array(floats[8...11]))
let f3 = float4(Array(floats[12...15]))
self = simd_float4x4(f0, f1, f2, f3)
}
}
测试
let col0 = float4(0.1, 0.2, 0.3, 0.4)
let col1 = float4(1.1, 1.2, 1.3, 1.4)
let col2 = float4(2.1, 2.2, 2.3, 2.4)
let col3 = float4(-3.1, -3.2, -3.3, -3.4)
var x = simd_float4x4(col0, col1, col2, col3)
print(x)
let xDesc = x.debugDescription
if let y = simd_float4x4(xDesc) {
print(y)
}
输出
simd_float4x4([[0.1, 0.2, 0.3, 0.4)], [1.1, 1.2, 1.3, 1.4)], [2.1, 2.2, 2.3, 2.4)], [-3.1, -3.2, -3.3, -3.4)]]) simd_float4x4([[0.1, 0.2, 0.3, 0.4)], [1.1, 1.2, 1.3, 1.4)], [2.1, 2.2, 2.3, 2.4)], [-3.1, -3.2, -3.3, -3.4)]])