Cobie Fisher Cobie Fisher - 7 months ago 26
Swift Question

How to search and replace values in a Swift array?

I have an array:

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

(not necessarily in that order or numbers, could be: [4,9,15,12])

I want to replace all instances of 10 with A, 11 with B, 12 with C, 13 with D, 14 with E, 15 with F and then

outputLabel.text = array.joinWithSeperator("")


I already know that to replace words in a string you can:

var myString = "Hello this is a test."
var myDictionary = ["Hello":"Yo"]

for (originalWord, newWord) in myDictionary {
let newString = aString.stringByReplacingOccurrencesOfDictionary(myString, withString:newWord, options: NSStringCompareOptions.LiteralSearch, range: nil)
}


So would searching and replacing values in an array be something similar?

Answer

Do you mean converting numbers from 1 to 15 to their hex string representation?

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
let hexArray = array.map { String($0, radix: 16, uppercase: true) }