字符串转换在斯威夫特BOOL - 通过API或大部分斯威夫特式的方法 [英] Convert String to Bool in Swift - via API or most Swift-like approach
问题描述
有没有转换布尔值的最可能的字符串重新presentations(一个API,如真,真,假,假,是,否,1 0)到斯威夫特一个布尔?
Is there an API to convert most possible String representations of Boolean values (e.g. "True", "true", "False", "false", "yes", "no", "1", "0") into a Bool in Swift?
如果没有,会得到什么样雨燕最方式从头编码呢?难道是一个功能图()操作?还是其他什么东西?
If not, what would be the most Swift-like approach to coding this from scratch? Would it be a functional map() operation? Or something else?
在这种情况下原始源数据是JSON,但我有兴趣在解决最雨燕样的方式问题的可能,因此更多地了解在这个过程中语言的症结所在。
The original source data in this instance is JSON, but I'm interested in the crux of solving the problem in the most Swift-like way possible and hence learning more about the language in the process.
推荐答案
有没有内置的方式AFAIK。类似的方法标准 toInt()
可以是:
There is not built in way AFAIK. Similar method to standard toInt()
could be:
extension String {
func toBool() -> Bool? {
switch self {
case "True", "true", "yes", "1":
return true
case "False", "false", "no", "0":
return false
default:
return nil
}
}
}
这篇关于字符串转换在斯威夫特BOOL - 通过API或大部分斯威夫特式的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!