I've reviewed a bit of Swift syntax, here's a highlight to save your time:
1. Type inference
Swift switch type declaration to facilitate "type-inference".
Int swiftVar ; // old c-style
var swiftVar : Int = 1 // type "Int" is now declared at the front
var swiftVar = 1 // type of swiftVar has been inferred as "Int"
It also means that Swift is a type-safe language i.e it needs to be specifically typed. Not like scripting language like JavaScript where you can just define any variable and not care about the type.
2. Typealias
Just like typedef, we can define it as
typealias myType = Uint16
var yourType = myType.min
3. Constant v Variables
Constant is declared as "let" (C++ is "const").
let x = "Hello"
x = "World" //compile error ! changing const value
3. Integer conversion
Swift has a few built-in integer classes that is important for us to know:
Uint8, Uint16, Uint32, Uint64
If you define Uint, it'll be defined based on the platform (Uint32 on 32-bit platform, Uint64 on 64-bit platform).
Conversion between these integer type variables must be done explicitly (Yawn).
let myInt : Uint8 = 1
let myBigInt: Uint16 = 2000
let newInt = myBigInt + Uint16(myInt)
4. Tuple
I like this Tuple stuff. I am longing to have this in C-style language (despite the fact that it is so easy to have tuples in scripting language) .
let myBook = ( 1181818 , "Riding Bus for Dummies") // declare the tuple
let (code, title ) = myBook // extract the tuples and place it nicely into the variable "code" and "title"
println ("The book code is \(code) and the title is \(title) ")
This reminds me of php "explode" function
5. Optionals
I was thinking hard about Swift syntax called "optionals", and I realized that this is probably coming from C-style conditional check:
(testValue) ? "this value " : "another value" ;
If I write this logic based on Swift's "Optional" , it is more like this:
(testValue) ? "this value" : nil
But in swift, it is more than you think.
Int? // yes, this is what we call optional.it means, this value is either of type Int, or nil
var myInt:Int? = 2
println(myInt!)
Int! // implicitly unwrapped the optional when you try accessing it
var myInt:Int! = 2
println(myInt) // no exclamation mark. I wonder why they do this.
Enough for now.
A place to breathe
Sunday, July 6, 2014
Subscribe to:
Post Comments (Atom)
About Me
- syamsulhasran
- I'm currently a software engineer. My specific interest is games and networking. I'm running software company called Nusantara Software.
No comments:
Post a Comment