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?
[] is just an empty array of the type you defined.
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.
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'.
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.
Ok, this is the meaning of
var treasures: [Treasure] = []
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With