2

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?

3 Answers 3

3

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) }
Sign up to request clarification or add additional context in comments.

Comments

0

You can simply use something like this:

let integers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
let a = UnicodeScalar("A").value
let string = String(integers.map { Character(UnicodeScalar(UInt32($0) + a - 1)) })
// => string is now "ABCDEFGHIJKLMNO"

Comments

0

You can do this by using the map function which due to type inference can be very concise if you are consistent with types:

let original = [1,2,3]
let substitutionDictionary = [1: "A", 2: "B", 3: "C"]
let substituted = original.map { substitutionDictionary[$0]! } // ["A","B","C"]

I am not making any assumptions about your intentions regarding ASCII conversion from number to character. This is a generic approach.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.