is it possible convert String to simd_float4x4 ? ( iOS 12 )

梦想的初衷 提交于 2019-12-11 11:27:30

问题


is it possible to construct simd_float4x4 from a string, eg: I had a string which stored simd_float4x4.debugdescription's value ?


回答1:


Here is an extension for simd_float4x4 that adds a failable init that takes a debug description and creates the simd_float4x4. It is a failable init because the string might be ill formed.

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)
    }
} 

Test

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)
}

Output

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)]])


来源:https://stackoverflow.com/questions/51579408/is-it-possible-convert-string-to-simd-float4x4-ios-12

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!