Seth Rodgers Seth Rodgers - 5 months ago 13
Swift Question

How do I replace an item in array with another item in a different array?

I know the basic way of replacing an item in a string, but now how I am doing it. Here's my code. I'm trying to search a note for certain words and swap them out when I do find them. I have certain words to replace other certain words with and I need to match them up so the sentence still makes sense.

func searchNote1()
{
let contentArr = note1.content.componentsSeparatedByString(" ")
let count = contentArr.count
var num = 0
while num < count
{
if conciseArr.contains(contentArr[num])
{
contentArr[num] = conciseArr []
}
num += 1
}
}


I am trying to replace the string in contentArr[num] (wherever a certain word is found) and swap it out with the string found in conciseArr. Where I am stuck is how do I know the location of the word in conciseArr to replace the other word with?

Answer

Rather than .contains, look at indexOfObject. If the object exists in the conciseArray, you will get the index (location), otherwise you will get an NSNotFound. Then, if (location != NSNotFound)... (do your swap using the known indices)

And, while we're at it, perhaps fast enumeration would be appropriate here? (I'm an Obj-C guy; I hope my Swift syntax is right!)

func searchNote1()
{
    let contentArr = note1.content.componentsSeparatedByString(" ")
    for (index, element) in contentArr.enumerate()
    {
        var location = conciseArr.indexOfObject(element)
        if (location != NSNotFound)
        {
            contentArr[index] = conciseArr[location]
        }
    }
}
Comments