0

Say I have the following array:

var questions = ["Is he great?", "Is he nice?", "Is he wonderful?"]

How can I alter it so that if I call any element from this array, the 'he' is substituted for 'she'? I've tried map, but this only seems to work for individual elements, and not parts of an element. Slicing is also only inter-element, and replaceOccurrence creates a new string, but doesn't alter the original. Ideally I'd like to write:

print(questions[0])

and get: "Is she great?" for any element in the array containing 'he' without having to create a whole new array. TIA.

Jake Jake
  • 9
  • 4
  • 1
    Use map and create a new array. Inside the closure for your map statement, use string parsing to replace "he" with "she". You'll have a different array at the end. Alternately, create a function that takes a string as input and returns a string with "he" replaced with "she". Let's call it `transformString(_:)`. Then use `transformString(questions[0])` – Duncan C Aug 22 '22 at 17:37
  • If you **do not** want to alter the original array, then this will print what you want: `print(questions[0].replacingOccurrences(of: " he ", with: " she "))`. I you **do want** to change the original array, then use this: `questions = questions.map {$0.replacingOccurrences(of: " he ", with: " she ")}`, will do it, using `print(questions[0])` – workingdog support Ukraine Aug 22 '22 at 23:03
  • thanks, these are helpful - the last line worked, but I'm thinking now my problem lies in a different area – Jake Jake Aug 23 '22 at 08:39

1 Answers1

0

I am not sure why you want to avoid creating a new array, but if you're determined to avoid making new arrays, consider an array of functions that return the thing you want, like:

var sheOrHe = "he"

func f(_ s: String) -> () -> String {
    return { "Is \(sheOrHe) \(s)?" }
}

let qFuncs = [f("great"), f("nice"), f("wonderful")]

qFuncs[0]() // "Is he great?"

sheOrHe = "she"

qFuncs[0]() // "Is she great?"

Or without closing over the sheOrHe var:

func f(_ s: String) -> (String) -> String {
    { sheOrHe in "Is \(sheOrHe) \(s)?" }
}

let qFuncs = [f("great"), f("nice"), f("wonderful")]

qFuncs[0]("he") // "Is he great?"

qFuncs[0]("she") // "Is she great?"

Or without storing the functions:

func areThey(_ s: String) -> (String) -> String {
    { sheOrHe in "Is \(sheOrHe) \(s)?" }
}

let adjectives = ["great", "nice", "wonderful"]

areThey(adjectives[0])("he") // "Is he great?"

areThey(adjectives[0])("she") // "Is she great?"
Shadowrun
  • 3,572
  • 1
  • 15
  • 13