arrays - 如何在 Swift 中转换字符串?

标签 arrays swift swift3 swift-string

我有两种情况需要将字符串转换为不同的格式。

例如:

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/

相关文章:

ios - 如何只为 UILabel 的左上角设置 cornerRadius?

ios - swift 3 - ViewController 不取消选择 UITableView 中的选定行

html - 在 Angular 2 和 Typescript 的数组中定义数组

ios - 如何从具有多个数组和括号的大型 JSON 响应中获取值?

ios - 我想让用户选择使用相机拍照或从库中挑选照片(ios-swift,苹果示例-foodtracker)

ios - 如何创建像这样的 Onboarding/WalkThrough/App-intro swift 3

ios - 在 VIPER 项目中启用 lightContent 状态栏样式

arrays - f# 找出 2 个 obj[] 列表之间的差异

c++ - "new Classname*[]"是什么意思?

c++ - c++ ifstream 中的 Getline 导致不需要的行为?