Last active
August 2, 2022 12:48
-
-
Save A86S/0513b68c3c4507ecd23f1ce762c57bcc to your computer and use it in GitHub Desktop.
Swift Basics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// variable and constant | |
var a = 10 // variable can be updated later | |
let PI = 3.14 // can not modify later | |
// Data types (Int, Float, Bool, Double, String) or Type Annotations | |
var age: Int = 10 | |
var name:String = "John" | |
var radius: Float = 2.5 | |
var area: Double = 14.50 | |
var isAlive: Bool = false | |
// joining strings | |
var name = "Smith" | |
var age = 30 | |
var userInfo = "User name is \(name) and his age is \(age)" | |
print(userInfo) | |
// if - else | |
if age > 18 { | |
print("\(name) can vote") | |
}else { | |
print("\(name) can not vote") | |
} | |
//switch statement | |
var dayOfWeek: Int = 3 | |
switch dayOfWeek { | |
case 1,2,3,4,5,6,7: | |
print("It is a week day") | |
default: | |
print("Wrong input : it's not a week day ") | |
} | |
// ternary operator | |
var canVote = age >= 18 ? true : false | |
print("You can vote : \(canVote)") | |
// for loop | |
var sum:Int = 0 | |
for index in 1...5 { | |
sum += index | |
} | |
print("sum of 1 to 5 is ", sum) | |
// while loop | |
var tableNo = 2 | |
var counter = 1 | |
while(counter <= 10) { | |
print(tableNo , "*", counter, "=", counter * tableNo) | |
counter+=1 | |
} | |
// repeat loop | |
tableNo = 2 | |
counter = 1 | |
repeat { | |
print(tableNo , "*", counter, "=", counter * tableNo) | |
counter+=1 | |
} while(counter <= 10) | |
// functions | |
func greetings() { | |
print("Hello Sir/Madam") | |
} | |
// passing parameters | |
func greetingUser(user:String) { | |
print("Hello, ",user) | |
} | |
// return values | |
func addTwoNUmbers(num1: Int, num2: Int) -> Int { | |
return num1 + num2 | |
} | |
//greetings() | |
greetingUser(user: "John") | |
print("Func Add 2 numbers ", addTwoNUmbers(num1: 10, num2: 20)) | |
// return multiple values | |
func getUser() -> (firstName: String, lastName: String) { | |
(firstName: "Tom", lastName:"Cruise") | |
} | |
let user = getUser() | |
print("User \(user.firstName) last name is : \(user.lastName)") | |
let (firstName, _) = getUser() | |
print("User \(firstName)") | |
// class | |
class BlogPost { | |
var title:String? = nil; | |
var body:String? = nil; | |
var author:String? = nil; | |
var publishDate:String? = nil; | |
} | |
var b = BlogPost() | |
print(b.title ?? "No title found") | |
b.title = "Swift for beginners" | |
print(b.title ?? "No title found") | |
// inheritance | |
class Laptop { | |
var weight: Float = 2.8 | |
var color : String = "Black" | |
func bootSpeed() { | |
print("Old Laptop take 15 seconds in booting") | |
} | |
} | |
class MacBook : Laptop { | |
override func bootSpeed() { | |
//super.bootSpeed() | |
print("New M1 chip can boot in 3-4 seconds") | |
} | |
} | |
var oldLaptop = Laptop() | |
oldLaptop.bootSpeed() | |
var m1MackBook = MacBook() | |
print("Macbook color is \(m1MackBook.color)") | |
m1MackBook.bootSpeed() | |
// initializers and optionals | |
class Person { | |
var name:String? | |
var age:Int? | |
var behaviour: String? | |
// init() { | |
// print("called init method") | |
// name = "John" | |
// age = 30 | |
// } | |
init(_ name:String, _ age:Int) { | |
self.name = name | |
self.age = age | |
} | |
convenience init(behaviour: String){ | |
self.init("Max", 24) | |
self.behaviour = behaviour | |
} | |
} | |
var a1 = Person("John", 30) | |
a1.name | |
a1.age | |
a1.behaviour | |
var b1: Person? | |
b1 = a1 | |
b1?.age | |
a1.age = 35 | |
b1?.age = 40 | |
a1.age | |
if let canVote = a1.age { | |
if(canVote > 18){ | |
print("Yes you can vote") | |
}else{ | |
print("No you can not vote") | |
} | |
} | |
var hasIdentity: Bool { | |
return a1.name != nil | |
} | |
print("user a has idendity \(hasIdentity)") | |
if let aBehaviour = a1.behaviour { | |
print("A's Behaviour \(aBehaviour)") | |
}else { | |
print("A has no Behaviour") | |
} | |
let c = Person(behaviour: "is a Good Person") | |
print("C ", c.behaviour ?? "has no behaviour") | |
print("C name is \(c.name ?? "") and age is \(c.age ?? 0 )") | |
// Array | |
var employeeArray = ["John", "Max", "Nick"] | |
// other way is => var employeeArray = [String]() | |
print(employeeArray) | |
print("Total Employees \(employeeArray.count)") | |
print("access 0th index -> \(employeeArray[0])") | |
// traverse | |
for employee in employeeArray { | |
print(employee) | |
} | |
employeeArray[0] = "Kumaar" | |
print(employeeArray) | |
// Dictionaries (Collection for key-value pair) | |
var employeesDict = ["name": "John", "Job":"Swift Developer"] | |
print(employeesDict["name"]!) | |
print(employeesDict.popFirst()!) | |
var countries = Dictionary<String, String>() | |
//var countries = [String:String]() | |
countries["IN"] = "India" | |
countries["US"] = "America" | |
for (code, country) in countries { | |
print("Country Code : \(code) - \(country)") | |
} | |
// Sets (collection with no order and no duplicates values) | |
var numbers = Set([1,2,2,1,3,7,6,5,3]) | |
print(numbers) | |
// Enum | |
enum weekDays { case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday , Sunday} | |
var day = weekDays.Monday | |
day = .Friday | |
print(day) | |
print(weekDays.Monday) | |
// Handling errors | |
enum EmailError : Error { | |
case invalid | |
} | |
func checkEmail(_ email:String!) throws -> String { | |
if(email == nil) { | |
throw EmailError.invalid | |
} | |
if(!email.contains("@")){ | |
throw EmailError.invalid | |
} | |
return "Valid Email" | |
} | |
do { | |
let result = try checkEmail("abc") | |
print(result) | |
}catch EmailError.invalid { | |
print("Not a valid email") | |
}catch { | |
print("wrong input") | |
} | |
// Closures | |
let oddEvenNumbers = [1,2,3,4,5,6,7,8,9] | |
let onlyOdd = oddEvenNumbers.filter({ (item : Int ) -> Bool in | |
return item % 2 != 0 | |
}) | |
print(onlyOdd) | |
// short operation with closures | |
let onlyEven = oddEvenNumbers.filter { $0 % 2 == 0 } | |
print(onlyEven) | |
// In Swift, structs are value types whereas classes are reference types. When you copy a struct, you end up with two unique // copies of the data. When you copy a class, you end up with two references to one instance of the data. It's a crucial // // difference, and it affects your choice between classes or structs. | |
// Structs | |
struct Car { | |
var color : String | |
var speed : Int | |
var gear: Int = 4 // default value | |
var onSale : Bool = true | |
// if you want to update struct value, use mutating | |
mutating func stopSales() { | |
onSale = false | |
} | |
} | |
var carA = Car(color: "Red", speed: 180, gear: 5) | |
var carB = Car(color: "Grey", speed: 100) | |
print(carA) | |
print(carB) | |
// Property Observers | |
struct Weather { | |
var temperature = 0 { | |
didSet { | |
print("temperature is now \(temperature) degree") | |
} | |
} | |
} | |
var weather = Weather() | |
weather.temperature += 15 | |
weather.temperature -= 10 | |
// Access Modifiers & static properties | |
struct Student { | |
static let className = "First Standard" | |
private(set) var name : String | |
private(set) var grade: String | |
mutating func updateGrade(newGrade : String) { | |
self.grade = newGrade | |
} | |
} | |
var st = Student(name: "John", grade: "A") | |
st.updateGrade(newGrade: "A+") | |
// st.name = "Smith" // not allowed for private members | |
Student.className | |
print(st) | |
// Protocols | |
protocol Person { | |
var name: String { get } | |
var age: Int { get set } | |
func PersonHabbits(for habbits: String) -> String | |
} | |
class Male : Person { | |
var age: Int = 0 | |
let name : String = "John" | |
func PersonHabbits(for habbits: String) -> String { | |
habbits | |
} | |
} | |
var male = Male() | |
male.age = 24 | |
male.PersonHabbits(for: "Watching football") | |
// Extensions | |
extension Collection { | |
var isNotEmpty : Bool { | |
isEmpty == false | |
} | |
} | |
let games = ["Football", "Hockey", "Baseball"] | |
if games.isNotEmpty { | |
print("Total games are \(games.count)") | |
} | |
// guard optional | |
func printAge(of age: Int?) { | |
guard let age = age else { | |
print("please provide age") | |
return | |
} | |
print("Your age is \(age)") | |
} | |
printAge(of: nil) | |
printAge(of: 20) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment