in most cases,If we want to get the contents of a section of the array (for example, front-to-middle,Some of the values of the array or the last),This time you need to traverse the array to assign a new array:
1 2 3 4 5 6 7 |
let fixedArray = [1,2,3,4,5,6] var myArray:[Int] = [] for (i,n) in fixedArray.enumerate() { if i > 3 {break} myArray.append(n) } |
Such an array of short, better said it does not matter,However, if the array is relatively large and we need to value and more,It is clear that it is a waste of time to traverse up。
Swift in itself provides an array of features split,This mechanism is called SubSequence type,It provides an array of sub-sequences:
1 2 |
public func prefix(maxLength: Int) -> Self.SubSequence public func suffix(maxLength: Int) -> Self.SubSequence |
Obviously,There is provided a front or from the start of the specified number of array split,In fact, there are many more methods of resolution here I will not go into details,You can go to look at the specific declaration in Xcode。
But it is worth mentioning that,Split out of sequence,Remains the original array index value - of course,Array is a value type,So the operation of the sub-sequence does not affect the original array:
1 2 3 4 5 |
var sub = fixedArray.suffix(2) sub[5] = 8 print(sub[5]) print(fixedArray) |
Here we take two values from the forward post,Visible sequence subscript index is still before the array fixedArray Continuation of,I put the word sequence to declare variables,You can modify the,The original array value remains unchanged。
This time if you want to use sequences that direct use of the,It has exactly the same with the array method。
but
It can not be used as an array,It also did not return an array of methods!
1 2 3 |
error: cannot assign value of type 'ArraySlice<Int>' to type '[Int]' someArray = sub ^~~ |
To re-assigned to an array type variable,Then you must use an array initializers to initialize it:
1 2 |
var someArray:[Int] = [] someArray = Array(sub) |
Then,Finally, we show you how to quickly remove one from the first three values in an array as a new array:
1 2 3 4 |
let fixedArray = [1,2,3,4,5,6] var myArray:[Int] = Array(fixedArray.prefix(3)) |
Yes,Just a word。
Extended reading
Slice(An array of segmented operation)
Security snoop array index of the array of slices Swift
Original article written by LogStudio:R0uter's Blog » Swift set cut scores
Reproduced Please keep the source and description link:https://www.logcg.com/archives/1936.html