My first week of learning Swift.
Awdesh Sep 14 Updated on Sep 16, 2018
1.) Declaring constants and variables.
Constants: Once declared their value can't be changed. Swift will throw compile time error when trying to update the value.
2.) Declaring a function
Java's syntax of a regular function looks like below
3.) Class function
Like python, swift has class functions. Class functions are bound to a class rather than an instance of a class. Honestly,
function followed by
class in the syntax threw me off a bit when I first encountered it in the source code.
Python's syntax of a class function
4.) Using underscore
In my very short experience with Swift, I have seen the use of
_ inside function calls.
_ is used to define an unnamed parameter inside the function. Swift uses a name for each parameter so when we call a function we need to provide the name of the parameter.
_ can bypass passing of the name altogether. Let's walk through an example-:
In general, when
_ in front we can to ignore value. Another use case of
_ would be something like below.
5.) Type Alias
This is certainly not the best use case of using type aliases. The better use case is by aliasing closures inside the function. Functions and closures in swift have a parameter type and a return type which can be aliased.
As per Apple docs
Closures are self-contained blocks of functionality that can be passed around and used in your code.
! is used for Optionals in swift. Use of optionals can make variable to have a value or nil.
? is used after the variable type indicate that the variable is optional.
! is used to unwrap the value of optional so to use it.
We could check for non-nil before unwrapping optional to get rid of runtime error.
As pointed out by Nuno Vieira in the comment section, force unwrapping is not a good practice rather we can use (if..let) which is called Optional binding method.
8.) Dictionary and Array
This is it for this post. Stay tuned for articles like this.
- Offical swift tutorial from Apple-: https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html
- Great read about Optionals-: https://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift
If you want me to write on a specific topic, please feel free to post them in the comment section.