Using The XCode Playground

Hello World:
In Swift, the traditional “Hello World” program is very simple. Open Xcode and create a new project. Select “Command Line Tool” as the project template and choose “Swift” as the language. In the main.swift file, type the following code:
1 | print("Hello, World!") |
Click the “Run” button to build and run the program. You should see the output “Hello, World!” displayed in the console.
Basic Syntax:
In Swift, a function is defined using the following syntax:
1 2 3 4 | func functionName(arg1: Type, arg2: Type) -> ReturnType { // Function body return returnValue } |
For example, to define a function that adds two numbers, you could write:
1 2 3 | func add(x: Int, y: Int) -> Int { return x + y } |
You can also use the shorthand syntax for single-expression functions:
1 2 3 | func add(x: Int, y: Int) -> Int { x + y } |
To call a function, you simply write the function name followed by the arguments in parentheses:
1 | let result = add(2, 3) |
This will set the variable “result” to 5.
1 2 3 4 | // This is a comment. /* This is also a comment but is written over multiple lines. */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Keywords Class deinit Enum extension Func import Init internal Let operator private protocol public static struct subscript typealias var break case continue default do else fallthrough for if in return switch where while as dynamicType false is nil self Self super true _COLUMN_ _FILE_ _FUNCTION_ _LINE_ associativity convenience dynamic didSet final get infix inout lazy left mutating none nonmutating optional override postfix precedence prefix Protocol required right set Type unowned weak willSet |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // Types Int8 1byte -127 to 127 UInt8 1byte 0 to 255 Int32 4bytes -2147483648 to 2147483647 UInt32 4bytes 0 to 4294967295 Int64 8bytes -9223372036854775808 to 9223372036854775807 UInt64 8bytes 0 to 18446744073709551615 Float 4bytes 1.2E-38 to 3.4E+38 (~6 digits) Double 8bytes 2.3E-308 to 1.7E+308 (~15 digits) Bool String Character Optional Tuple // Type Alias typealias newname = type // Type Safety var varA = 42 varA = "This is hello" // Error, type defined prev as int // Type Inference var varI = 42 // Type infered as Int var varS = "Meaning of life" // Type infered as String |
1 2 3 4 5 6 7 8 9 10 | // Variables var var1 = 42 // Variable let var2 = 42 // Constant var var3 : Int32 = 42 // Variable declared as Int 32 var var4 : Float = 33.45 // Variable declared as Float var var6 : Bool = true // Variable declared as Boolean var var7 : String = "Hello" // Variable declared as String |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // Optionals var isItInt1: Int? // Default value = nil var isItInt2: Int? = nil // Same as IsItInt1 var isItString: String? // Default value = nil if let yourString = isItString { // Available as temp value print("Your string has - \(yourString)") } else { print("Your string does not have a value") } if isItString != nil { print(isItString!) // Unwrap the value using ! } else { print("IsItString has nil value") } var myString:String! = "Hello, Swift 4!" if myString != nil { print(myString) // Automatically unwrapped as declared with ! } else { print("myString has nil value") } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Tuples var myTuple = ("keith", "programmer", 56) myTuple.0 == "keith myTuple.1 == "programmer" myTuple.2 == 56 var myTuple2 = (name: "keith", role: "programmer", age: 56) myTuple2.name == "keith myTuple2.role == "programmer" myTuple2.age == 56 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | // Operators // Arithmetic + Adds two operands A + B will give 30 − Subtracts second operand from the first A − B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by denominator B / A will give 2 % Modulus Operator and remainder of after an integer/float division B % A will give 0 // Comparison == Checks if the values of two operands are equal or not; if yes, then the condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not; if values are not equal, then the condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. (A <= B) is true. // Logical && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. !(A && B) is true. // Bitwise & Binary AND Operator copies a bit to the result, if it exists in both operands. (A & B) will give 12, which is 0000 1100 | Binary OR Operator copies a bit, if it exists in either operand. (A | B) will give 61, which is 0011 1101 ^ Binary XOR Operator copies the bit, if it is set in one operand but not both. (A ^ B) will give 49, which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61, which is 1100 0011 in 2's complement form. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. (A << 2 will give 240, which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15, which is 0000 1111 // Assignment = Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts right operand from the left operand and assigns the result to left operand C -= A is equivalent to C = C - A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assigns the result to left operand C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assigns the result to left operand C %= A is equivalent to C = C % A <<= Left shift AND assignment operator C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator C &= 2 is same as C = C & 2 ^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2 |= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2 |
1 2 3 4 5 6 7 8 | // Ranges Closed Range (a...b) defines a range that runs from a to b, and includes the values a and b. 1...5 gives 1, 2, 3, 4 and 5 Half-Open Range (a..< b) defines a range that runs from a to b, but does not include b. 1..< 5 gives 1, 2, 3, and 4 One- sided Range a… , defines a range that runs from a to end of elements …a , defines a range starting from start to a 1… gives 1 , 2,3… end of elements …2 gives beginning… to 1,2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // If statements if boolean expression { // do something } if boolean expression { // do something } else { // do something else } Exp1 ? Exp2 : Exp3; if boolean expression { // do this } else if boolean expression { // do that else { // do something else } if boolean expression { if boolean expression { // do something } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //. Switch switch expression { case expression1 : statement(s) fallthrough /* optional */ case expression2, expression3 : statement(s) fallthrough /* optional */ default : /* Optional */ statement(s); } switch expression { case expression1 : statement(s) fallthrough /* optional */ case expression2, expression3 : statement(s) fallthrough /* optional */ default : /* Optional */ statement(s); } |
1 2 3 4 5 6 | // for loop var someInts:[Int] = [10, 20, 30] for index in someInts { print( "Value of index is \(index)") } |
1 2 3 4 5 6 7 | // while loop var index = 10 while index < 20 { print( "Value of index is \(index)") index = index + 1 } |
1 2 3 4 5 6 | // repeat while loop repeat { statement(s); } while( condition ); |
1 2 3 4 5 6 7 8 9 10 11 12 | // break & continue repeat { index = index + 1 if( index == 15 ){ break // Exit loop early at 15 } if index == 13 { continue // Skip 13 } print( "Value of index is \(index)") } while index < 20 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | // Strings var string1 = "Hello, World!" var string2 = String(""Hello, World!"") let string3 = """ a multi line string spread across 3 lines """ var string4 = "" // Empty String string4.isEmpty == true let string5 = "I am immutable" string5.count == 14 for chars in string5 { print(chars) } var varA = 20 let constA = 100 var varC:Float = 20.0 var stringA = "\(varA) times \(constA) is equal to \(varC * 100)" print( stringA ) isEmpty hasPrefix(prefix: String) hasSuffix(suffix: String) toInt() count() utf8 utf16 unicodeScalars + += == < startIndex endIndex Indices insert("Value", at: position) remove(at: position) removeSubrange(range) reversed() |
1 2 3 4 | // Characters let char1: Character = "A" let char2: Character = "" // Empty char |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // Arrays var someArray = [SomeType]() var someArray = [SomeType](count: NumbeOfElements, repeatedValue: InitialValue) var myArray1 = [Int]() var myArray2 = [Int](count: 10, repeatedValue: 0) var myArray3:[Int] = [10, 20, 30] myArray3[0] == 10 myArray3.append(40) myArray3 += [50] myArray3[4] = 60 myArray3.count == 5 myArray3.isEmpty == false for item in myArray3 { print(item) } for (index, item) in myArray3.enumerated() { print("Value at index = \(index) is \(item)") } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // Sets var name = Set<Type>() var mySet = Set<Int>() mySet.count == 0 mySet.isEmpty == true mySet.insert(1) mySet.insert(2) mySet.count == 2 mySet.isEmpty == false mySet.remove(1) mySet.contains(1) == false mySet.count == 1 for items in mySet.sorted() { print(mySet) } var mySet1 = Set<Int>(1, 3, 5, 7, 9) var mySet2 = Set<Int>(1, 2, 4, 6, 8) mySet1.union(mySet2) mySet1.intersection(mySet2) mySet1.subtracting(mySet2) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // Dictionaries var someDict = [KeyType: ValueType]() var someDict1 = [Int: String]() = [1: "One", 2: "Two", 3: "Three"] var someDict2 = [String: String]() = ["Name": "Keith", "Job": "Programmer"] var heroes = ["Iron Man", "Thor", "The Hulk", "Ant Man"] var ranking = [1, 2, 2, 4] var combined = Dictionary(uniqueKeysWithValues: zip(heroes, ranking)) combined.count == 4 combined.isEmpty == false combined["Iron Man"] == 1 combined.updateValue("The Hulk", forKey: 3) combined["Ant Man"] = 5 combined.removeValue(forKey: "Ant Man") var highest = combined.filter { $0.value < 3 } var byRanking = Dictionary(grouping: combined ) { $0.value } for (index, keyValue) in combined.enumerated() { print("Dictionary key \(index) - Dictionary value \(keyValue)") } let dictKeys = [Int](combined.keys) let dictValues = [String](combined.values) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | // Functions func funcname(Parameters) -> returntype { Statement1 Statement2 --- Statement N return parameters } func sayHello() { print("Hello!") } func addTwo(first:Int, second:Int) -> Int { return first + second } func getDetails(name: String) -> (name:String, age:Int, job:String) { return (name, 55, "programmer") } // Optional Return parameters func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) { print("min is \(bounds.min) and max is \(bounds.max)") } // External Parameter Names func myFunc(firstArg first:Int, secondArg second:String) -> String { return "Not sure why?" } // Variadic Paremeter func myFunc(params....) { for p in params { print(p) } } // Inout parameters func swap(a1: inout Int, b1: inout Int) { let t = a1 a1 = b1 b1 = t } var first = 2 var second = 10 temp(a1: &first, b1: &second) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Closures { (parameters) −> return type in statements } let sayHello = { print("Hello!") `} let sayHi = { (name: String) print("Hello" + name) } let createGreeting = { (name: String) -> String return "Hello, " + name } // Shorthand parameters var shorthand: (String, String) -> String shorthand = { print($1) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | // Enumerations enum names { case Swift case Closures } var lang = names.Closures lang = .Closures switch lang { case .Swift: print("Welcome to Swift") case .Closures: print("Welcome to Closures") default: print("Introduction") } enum Student { case Name(String) case Mark(Int,Int,Int) } var studDetails = Student.Name("Swift 4") var studMarks = Student.Mark(98,97,95) switch studMarks { case .Name(let studName): print("Student name is: \(studName).") case .Mark(let Mark1, let Mark2, let Mark3): print("Student Marks are: \(Mark1),\(Mark2),\(Mark3).") } enum Month: Int { case January = 1, February, March, April, May, June, July, August, September, October, November, December } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Structures struct studentMarks { var mark1 = 100 var mark2 = 200 var mark3 = 300 } let marks = studentMarks() struct studentMarks { var mark1:Int var mark2:Int var mark3:Int func init(m1:Int, m2:Int, m3:Int) { self.mark1 = m1 self.mark2 = m2 self.mark3 = m3 } } let marks = studentMarks(m1:100, m2:300, m3:500) |
Classes and Objects:
In Swift, classes and objects are defined using the following syntax:
1 2 3 | class MyClass { // Class members } |
For example, to define a class that represents a person, you could write:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Person { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } func sayHello() { print("Hello, my name is \(name).") } } |
You can create an instance of a class using the following syntax:
1 | let person = Person(name: "John", age: 30) |
You can access properties and call methods of the object using the “.” operator:
1 2 3 | person.sayHello() person.name == "John" person.age == 30 |
This will display the output “Hello, my name is John.” in the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Identity Operators === True if both objects are the same !== True if both objects are not the same class MyPerson: Equatable { let name: String init(n: String, a: Int) { name = n age = a } } func ==(lhs: MyPerson, rhs: MyPerson) -> Bool { return ((lhs.name == rhs.name) && ( lhs.age == rhs.age)) var class1 = MyPerson(n: "Keith", a: 55) var class2 = MyPerson(n: "Keith", a: 55) class1 === class2 // true class1 !== class2 // false } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | // Properties class Programmer { var name:String var age:Int var language:String let token:Striing = "XYZ" // Constant func init(name:String, age:Int, lang:String) { self.name = name self.age = age self.language = lang } } keith = Programmer("keith", 55, "Swift") keith.name == "keith" keith.age == 55 keith.language == "Swift" keith.age == 56 keith.token = "ABC" // Compile error // Lazy Stored Properties // Computed Properties // Setters & Getters // Read Only Computed Properties // Property Observers // Property Wrappers // Projected Values // Type Properties |
1 | // Methods |
1 | // Subscripts |
1 | // Inheritance |
1 | // Initialisation |
1 | // Deinitialiation |
1 | // ARC Overview |
1 | // Optional Chaining |
1 | // Type Casting |
1 | // Extensions |
1 | // Protocols |
1 | // Generics |
1 | // Access Control |