1

For example, I have an array like var myArray = ['player_static.png', 'player_run0.png', 'player_run1.png', 'player_run2.png', 'player_jump0.png', 'player_jump1.png']

Is there any simple way to get only the "player_runX.png" images?

2 Answers 2

3

You can use filter to get all elements that hasPrefix("player_run"):

let myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]

let playerRuns = myArray.filter{$0.hasPrefix("player_run")}
print(playerRuns)  //["player_run0.png", "player_run1.png", "player_run2.png"]
Sign up to request clarification or add additional context in comments.

1 Comment

like some music producers say: less is more. thanks ;)
1

One way to do this would be to iterate over the array and retrieve the elements that match the pattern. A very quick sample would be something like this:

var myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]

func getSubArray(array:[String],prefix:String) -> [String]
{
    var newArray = [String]()
    for img in array
    {
        if img.substringToIndex(img.startIndex.advancedBy(prefix.characters.count)) == prefix
        {
            newArray.append(img)
        }
    }
    return newArray
}

var test = getSubArray(myArray, prefix: "player_run")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.