Nitesh Nitesh - 3 months ago 9
Swift Question

Replace array contain according to its occurrences

How to replace number string with its corresponding Alphabet Characters in Array.

Example:
["1","2","3","3","2","3"]

Replace: 1 -> A, 2-> B, 3-> C

Result should be
["A","B","C","C","B","C"]

Answer

You may use Dictionary for replacement rules:

let array = ["1", "2", "3", "3", "2", "3"]

let replacementRules = ["1": "A", "2": "B", "3": "C"]

let result = array.map{replacementRules[$0] ?? $0}
print(result)
//["A", "B", "C", "C", "B", "C"]
Comments