有可能将String转换为simd_float4x4吗? (iOS 12)

时间:2018-07-29 10:32:19

标签: ios swift simd

是否可以从字符串构造simd_float4x4,例如:我有一个存储simd_float4x4.debugdescription值的字符串?

1 个答案:

答案 0 :(得分:2)

这里是extension的{​​{1}},其中添加了 failable simd_float4x4,该错误接受调试描述并创建init。这是失败 simd_float4x4,因为字符串可能格式错误。

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 { $0.filter { Array("-01234567890.").contains($0) } }
        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)
}