如何从Swift 4中的描述中解析数组? [英] How to parse array from description in Swift 4?
本文介绍了如何从Swift 4中的描述中解析数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Swift 4
,我有一个算法可以输出数组的基数为64的描述,如下所示:
I'm learning Swift 4
, and I have an algorithm that output the base 64 description of an array, like that:
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}
let output = [1, 2, 4, 65].description.toBase64()
print(output.fromBase64()) // "[1, 2, 4, 65]"
现在,我的问题是我需要将数组放回到Array
中,而不是在String
中.
我已经上网查询了,但是找不到这种类型的数组的解析方法(他们都在谈论JSON).
Now, my problem is that I need the array back in an Array
, and not as a String
.
I've looked up on the internet but I couldn't find a parsing method for this type of array (they were all talking about JSON).
推荐答案
以下是将字符串转换为Int
数组的方法:
Here is the way you can convert your string into Int
array:
var toString = output.fromBase64() //"[1, 2, 4, 65]"
if let str = toString {
let chars = CharacterSet(charactersIn: ",][ ")
let split = str.components(separatedBy: chars).filter { $0 != "" }.flatMap { Int($0)}
print(split) //[1, 2, 4, 65]
}
这篇关于如何从Swift 4中的描述中解析数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文