我有两种情况需要将字符串转换为不同的格式。
例如:
case 1:
string inputs: abc, xyz, mno, & llr // All Strings from a dictionary
output: ["abc","xyz", "mno", "llr"] //I need to get the String array like this.
但是当我使用这段代码时:
var stringBuilder:[String] = [];
for i in 0..<4 {
stringBuilder.append("abc"); //Appends all four Strings from a Dictionary
}
print(stringBuilder); //Output is 0: abc, 1:xyz like that, how to get desired format of that array like ["abc", "xyz"];
实际用法:
let arr = Array(stringReturn.values);
//print(arr) // Great, it prints ["abc","xyz"];
let context = JSContext()
context?.evaluateScript(stringBuilder)
let testFunction = context?.objectForKeyedSubscript("KK")
let result = testFunction?.call(withArguments:arr); // Here when I debugger enabled array is passed to call() like 0:"abc" 1:"xyz". where as it should be passed as above print.
其次,如何在 swift 中替换转义字符:我在 replaceOccurances(of:"\\'"with:"'");
中使用了“\”,但它没有变化。为什么以及如何逃避该序列。
case 2:
string input: \'abc\'
output: 'abc'
最佳答案
要将字典的所有值作为数组获取,您可以使用字典的 values
属性:
let dictionary: Dictionary<String, Any> = [
"key_a": "value_a",
"key_b": "value_b",
"key_c": "value_c",
"key_d": "value_d",
"key_e": 3
]
let values = Array(dictionary.values)
// values: ["value_a", "value_b", "value_c", "value_d", 3]
使用filter
,您可以忽略字典中所有不是String
类型的值:
let stringValues = values.filter({ $0 is String }) as! [String]
// stringValues: ["value_a", "value_b", "value_c", "value_d"]
使用 map ,您可以转换 stringValues
的值并应用您的 replacingOccurrences
函数:
let adjustedValues = stringValues.map({ $0.replacingOccurrences(of: "value_", with: "") })
// adjustedValues: ["a", "b", "c", "d"]
关于arrays - 如何在 Swift 中转换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107800/