Learning the Swift language is easy.
Here is the cheatsheet for your reference!
If you are new to Swift, get your hands dirty with the Challenges.
Print Hello World
print("Hello World")
Variable Mutable and Immutable
var mutableVar = "Hello" mutableVar = "World" let immutableVar = "Hello World"
Challenge
What happens when you set another value to
immutableVar
.Strong Typing and Inference
let stringVariable = "Type is inferred as String" let doubleVariable = 120.3 let explicitTyping: Int explicitTyping = 202
Challenge
What happens when you set the value of another type to the above variable?
Type Conversion
let one = 1 let oneHundred = "100" let sum = Int(oneHundred)! + one
String Interpolation
let integerInsideString = "I am Mozzlog. I was born at \(2023)"
Basic Data Type
let integerValue = 1 let doubleValue = 1.2 let floatValue: Float = 1.23 let stringValue = "this is string" let tupleValue = (integerValue, doubleValue, floatValue, stringValue)
Collection Basic : Array
let arrayOfString = ["Hello", "World"] let arrayOfInteger = [1, 2] let arrayOfDouble = [10.0, 21.2] let mixedArray: [Any] = ["String", 1, 10.2]
Challenge
What happens when you don’t set the explicit
[Any]
type to mixedArray
?Collection Key Value : Dictionary
let dictWithKeyStringAndValueString = [ "Hello": "World", "Good": "Morning", ] let dictWithKeyStringAndValueAny: [String:Any] = [ "Hello": 1, "Good": "Morning", ] let dictWithKeyAnyHashableAndValueString = [ "Hello": "World", 1: "Morning", ]
Challenge
What is the
AnyHashable
type?Collection Without Duplication: Set
let setOfNames: Set<String> = [ "Swift", "Kotlin" ]
Function
func sayHelloWorld() { print("Hello World") }
Function With Parameter
func sayMyName(name: String) { print("Your name is \(name)") } sayMyName(name: "Heissenberg")
Function With Return Value
func getReturnValue(_ value: Int) -> Int { return value } let value = getReturnValue(1002)
Function With Return Type Tuple
func createTuple(from value: Int) -> (Int, Int) { return (value, value) } let (value1, value2) = createTuple(from: 231)
Class
class StandardClass { }
Class With Member
class StandardClass { let member = "default" func printMember() { print(member) } } let object = StandardClass() object.printMember()
Class With Initializer
class StandardClass { let memberInt: Int var memberDefault = "" init(memberInt: Int, alternativeDefault: String = "") { self.memberInt = memberInt self.memberDefault = alternativeDefault } } let object = StandardClass(memberInt: 20) object.memberDefault = "changed" let object2 = StandardClass(memberInt: 20, alternativeDefault: "changed")
Struct
struct StandardStruct { let memberInt: Int var memberDefault = "" } let instance = StandardStruct(memberInt: 20) let instance2 = StandardStruct(memberInt: 20, memberDefault: "changed")
Challenge
Can you change the value of
memberDefault
after StandardStruct
instantiation?Hint
Use
var
instead of let
.