2

I have and array like this:

let array:Array<String> = ["name0","name1","name2","name3","name4","name5","name6"]

And now I wanna get

name0 , name1 , name2

. How to do this?

1
  • array[0 ... 2]. Commented Feb 17, 2018 at 9:00

2 Answers 2

4

You can get a slice using array[0 ... 2] or array[0 ..< 3] or array[..<3].

To convert it into a new array, you have to:

Array(array[0 ... 2])

but many operations can be done on the subsequence.

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

6 Comments

Ambiguous subscript with base type 'Array<String>' and index type 'CountableClosedRange<Int>'
dataSourceArr:Array<String> = array[0 ..< 3]
I set result in another array contains string value
@reza_khalafi The result you get is an ArraySlice, lose the :Array<String>. If you want to convert to an array, you have to wrap the result in Array(...) as I said in my answer. Also, please use the short type specifiers, e.g. [String] instead of Array<String>.
@reza_khalafi Nope, let dataSourceArr: [String] = Array(array[0 ..< 3]) or just let dataSourceArr = Array(array[0 ..< 3])
|
4

You can use this to get slice of an array :

let values = array[0...2]

Here you will know what else you can do : https://developer.apple.com/documentation/swift/arrayslice

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.