What is a slice in 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?

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])

Need Your Help

Using nested controllers

ruby-on-rails nested-resources

Since my site had an admin section and a normal (front-end user) section, I needed to structure the articles controller in such a way that it was RESTful.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.