1

I need to convert an array.count to String values for the count, i.e. array.count = 5 should return ["0","1","2","3","4"]

I've tried

var strRow = array.map { String($0) }
return strRow

but it's not working the way it should. Any help will be appreciated.

2
  • You still want the return to be an array? but of string? Commented Mar 8, 2016 at 13:21
  • That is correct yes. Commented Mar 8, 2016 at 13:32

3 Answers 3

3

Try

return Array(0...array.count)

if you want array of Strings, then just map it Array(0...array.count).map{String($0)}

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

3 Comments

I get an error "Value of type 'Int' has no member 'map'.
you are not copying correctly, probably you are mapping the count and not the array.
@CorBrink ogres answer is only one line of code compared to my answer. As he mentioned probably you are mapping the count. Try this var strArray = Array(0...array.count).map{String($0)} print(strArray)
1

Try this (Hint are in the Code Comments):

var array = [1, 2, 3, 4, 5] // array.count = 5
var stringArray = [String]()

// 0 ... array.count to go from 0 to 5 included
for index in 0 ... array.count {
    // append index with cast it to string
    stringArray.append(String(index))
}

print(stringArray)
// result -> ["0","1","2","3","4","5"]

Comments

1

In your question you give an example that array of count 5 should be transformed to ["0","1","2","3","4","5"], that's a 6-count array, are you sure this is what you need? I will assume that you want 5-count array to be transformed to ["0","1","2","3","4"], please correct me in the comments if I'm wrong.

Here's the solution I propose:

let array = [5,5,5,5,5] // count 5

let stringIndices = array.indices.map(String.init)
// ["0", "1", "2", "3", "4"]

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.