Continuation of Hacking With Swift 100 Days of Swift
Day 2 - Arrays, Dictionaries, Sets and Enums
Arrays are a standard, type declaration is not. instead of int[] in swift we do [Int]
Sets are quite simple, just use the named reserved function Set. Have in mind that these guys are unordered, not random, just unordered.
Talking about functions, in swift you only use func nameOfFunction(property: type), as a definer, but when you call them you need to do it weirdly as nameOfFunction(property: value).
Tuples like in .Net are fixed size, but have the advantage that can be named (iirc Named tuples only come later in .Net 8 or something).
Dictionaries are declared like in JavaScript, which btw accessing a none existing key instead of throwing an error returns nil (null in other languages, let's not talk about undefined), if you don't want nil to show you can use dictionary["nonExistingKey", default: "fallback string"]. Lastly, for type declaration we go as [String: otherType] ex [String: Double].
Enums are declared differently, but just a bit. Inside each option of an enum you'd have to add the reserved keyword
case
, which results inenum Directions { case north; case south }
and for specific values inside enums, works exactly like .Net. ALERT: the semicolon is only needed since this is an enum declared as a one liner, in a line break enum the semicolon is not required. Enums in swift can also have an associated value, where we can create something likeenum Weather { case sunny; case windy(speed: Int) }
and we would getwindy(speed: 25)
as a result.
Side note:
I need to look up for swift naming standards eventually.
Top comments (0)