Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a slice in Swift?

Tags:

slice

swift

What is a slice in Swift and how does it differ from an array?

From the documentation, the type signature of subscript(Range) is:

subscript(Range<Int>) -> Slice<T> 

Why not return another Array<T> rather than a Slice<T>?

It looks like I can concatenate a slice with an array:

var list = ["hello", "world"] var slice: Array<String> = [] + list[0..list.count] 

But this yields the error:

could not find an overload for 'subscript' that accepts the supplied arguments

var list = ["hello", "world"] var slice: Array<String> = list[0..list.count] 

What is a slice?

like image 787
hjing Avatar asked Jun 06 '14 02:06

hjing


People also ask

What is array slice in Swift?

Overview. The ArraySlice type makes it fast and efficient for you to perform operations on sections of a larger array. Instead of copying over the elements of a slice to new storage, an ArraySlice instance presents a view onto the storage of a larger array.

What is the use of slice ()?

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array.

What is slice and how does it work?

Slice is a Bengaluru-based payment and credit startup that extends hassle-free payment cards to deal with your daily payments, which can also be converted into Equated Monthly Installments or EMIs for the ease of the user without any added expense.

What is a slice data type?

slice is a composite data type and because it is composed of primitive data type (see variables lesson for primitive data types). Syntax to define a slice is pretty similar to that of an array but without specifying the elements count. Hence s is a slice.


1 Answers

The slice points into the array. No point making another array when the array already exists and the slice can just describe the desired part of it.

The addition causes implicit coercion, so it works. To make your assignment work, you would need to coerce:

var list = ["hello", "world"] var slice: Array<String> = Array(list[0..<list.count]) 
like image 176
matt Avatar answered Oct 12 '22 20:10

matt