Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax explanation: square brackets in Swift

Tags:

arrays

ios

swift

I'm studying Swift and got confusing with following syntax:

var treasures: [Treasure] = []

Treasure is custom class, declared as follow:

class Treasure: NSObject { }

In Objective-C square brackets mean method, but what do they mean in Swift?

like image 608
Evgeniy Kleban Avatar asked Dec 24 '14 14:12

Evgeniy Kleban


People also ask

What do square brackets mean in Swift?

[] is just an empty array of the type you defined.

What does square brackets mean in syntax?

mvBASIC Syntax NotationsAnything shown enclosed within square brackets is optional unless indicated otherwise. The square brackets themselves are not typed unless they are shown in bold. | A vertical bar that separates two or more elements indicates that any one of the elements can be typed.

What are square brackets used for in access to?

On SQL Server and MS Access, square brackets have a special meaning when used in a query filter. The square brackets are used to specify a set or range of characters, as in "[A-Z]" which would match any single character from 'A' to 'Z'.

What does angle brackets mean in Swift?

The angle brackets tell Swift that T is a placeholder type, which will be replaced with an actual type whenever the function is called. In this case, the Swift compiler ensures that any calls to count(of:in:) are passing in an array of the same type as the element argument.


1 Answers

Ok, this is the meaning of

var treasures: [Treasure] = []
  • var: you are declaring a variable
  • treasures: the name of your variable
  • [Treasure]: the type of your variable, in this case the type is Array of Treasure, the compiler will allow you to insert only object of type Treasure in your Array
  • []: the actual object (Array) referenced by your variable, in this case an empty Array.

E.g. if you want the Array to hold 2 elements you can write

var treasures: [Treasure] = [Treasure(), Treasure()]

Hope this helps.

Update: My example can also be written this way

var treasures = [Treasure(), Treasure()]

Infact thanks to the Type Inference the compiler can deduce the type of the variable treasures looking at the type of the assigned value.

like image 180
Luca Angeletti Avatar answered Oct 14 '22 19:10

Luca Angeletti