Skip to content

Instantly share code, notes, and snippets.

View JarvisTheAvenger's full-sized avatar
🎯
Focusing

Rahul Umap JarvisTheAvenger

🎯
Focusing
View GitHub Profile
import Foundation
// Property Observers - `willSet`, `didSet`
// Property observers let you observe the change in the state or value
// of properties and provides single source of truth
// 'didSet' and 'willSet' cannot be provided together with a getter
// If `set` is provided then it is mandotory to add `get`
import Foundation
// Opaque types
/*
A function or method with an opaque return type hides its return value’s type information.
Instead of providing a concrete type as the function’s return type, the return value is
described in terms of the protocols it supports. Hiding type information is useful at
boundaries between a module and code that calls into the module, because the underlying type of
the return value can remain private. Unlike returning a value whose type is a protocol type,
import Foundation
// Public vs Open
// properties and function declared using `public` or `open` access specifier is accessible outside module
// but in case of inheritance `public` swift compiler will not allow you to override it.
// Private vs FilePrivate
// Properties and Methods declared using `private` access specifier is accessible within declared type.
import Foundation
// Factory Design pattern
struct Person {
var name : String
}
class PersonFactory {
func createPerson() -> Person? {
nil
import Foundation
// Mutating function
// The properties of value types cannot be modified within its instance methods by default.
struct User {
var name : String
var age : Int
var address : String
import Foundation
// Result type is enum with two cases, success and error.
// Introduced in swift 5
enum ScoreboardError: Error {
case serverDown
case badURL
case unknown
}
import Foundation
// rethrowing function and method
// https://stackoverflow.com/questions/49672847/how-to-declare-a-rethrowing-function
/* A function or method can be declared with the rethrows keyword to indicate that it throws an error only
if one of its function parameters throws an error. These functions and methods are known as rethrowing functions and
rethrowing methods. Rethrowing functions and methods must have at least one throwing function parameter.
*/
import Foundation
// Keypath , WritableKeyPath, ReferenceWritableKeyPath
struct StarShip {
var name: String
var maxWrap: Double
}
var voyager = StarShip(name: "Voyager", maxWrap: 9.97)
import Foundation
// Init, Deinit
class User {
var name: String
var age: Int
var address: String
var emailID: String
// Failable + Designated Init
import Foundation
// Generics
/* Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.
*/
// Normal function
func add(first: Int, second: Int) -> Int {