1

Hi I have two arrays.

var firstArray = ["Hi", "Hello", "Mother"]
var secondArray = ["Yo", "Yee", "Father"]

Now say I did a println("I saw Johnny and said Hi") but it would really replace it with my second string object which is "Yo"

So pretty much replace everything in the first array with the second array in the exactly order they're in anytime someone typed any literal string in the first array? I'm trying to do this in swift. I tried looping through the first array with stringByReplacingOccurrencesOfString but I'm not sure how I can implement an NSArray into it. Any help?


What if I did below?

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)
}

I still can't figure out how if I put that into an println("hello how are you?) if it'll automatically know to replace "hello" every time it's entered in the println statement with "yo"

2 Answers 2

5

You're pretty close with your idea of using a dictionary, you just need to keep replacing myString instead of creating a new string each time, and call stringByReplacingOccurrencesOfString correctly:

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

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

println(myString)

Outputs:

Yo this is a test.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh wait, what if I had more then one key in the dictionary?
0

If the object in the array conforms to the Equatable protocol, (String does conform), then you can use find()

Try this in a playground:

import UIKit

var firstArray = ["Hi", "Hello", "Mother"]
var secondArray = ["Yo", "Yee", "Father"]

var index = find(firstArray, firstArray[0])

println("first string: \(firstArray[0])")
println("replaced: \(secondArray[index!])")

1 Comment

But the thing is, I want it to always replace these words. I want to type in a "println("Hello this is Dewan") and it'll always know to replace "Hello" with "Yo" You get what I mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.