Skip to content

Instantly share code, notes, and snippets.

@barabashd
Last active February 12, 2022 15:00
Show Gist options
  • Save barabashd/f450ad1230cdb83c83fd5f535c07f5cd to your computer and use it in GitHub Desktop.
Save barabashd/f450ad1230cdb83c83fd5f535c07f5cd to your computer and use it in GitHub Desktop.
import Cocoa
// MARK: - Protocols definition and syntax (2 slide)
// Declaration:
protocol SomeProtocol {
// protocol definition goes here
}
class Superclass {}
protocol ProtocolOne {}
protocol ProtocolTwo {}
// Conformance:
class SomeClass: Superclass, ProtocolOne, ProtocolTwo {
// class definition goes here
}
// MARK: - Property & method requirements (3 slide)
protocol TestProtocol: class {
var mustBeSettable: Int { get set }
var doesNotNeedToBeSettable: SomeClass? { get }
static var prefixSpecificationProperty: Int { get set }
func someMethod()
func someMethodWithParam(_ param: Any)
}
class TestClass: TestProtocol {
var mustBeSettable: Int {
get { return 10 }
set { print("mustBeSettable set") }
}
var doesNotNeedToBeSettable: SomeClass? { nil }
class var prefixSpecificationProperty: Int {
get { return 10 }
set { print("prefixSpecificationProperty set") }
}
func someMethod() {}
func someMethodWithParam(_ param: Any) {}
}
// MARK: - Optional requirements (4 slide)
@objc protocol OptionalProtocol {
@objc optional var someValue: Data? { get }
@objc optional func getData() -> Data
}
class OptionalClass {
var someReference: OptionalProtocol?
func updateData() {
if let data = someReference?.getData?() {
print(data)
} else if let someValue = someReference?.someValue {
print(someValue ?? "nil")
//someReference!.someValue
}
}
}
// MARK: - Mutating (5 slide)
protocol NotMutatingProtocol {
func upgrade()
}
protocol MutatingProtocol {
mutating func upgrade()
}
enum Position: MutatingProtocol {
case junior, middle, senior
mutating func upgrade() {
switch self {
case .junior:
self = .middle
case .middle:
self = .senior
case .senior:
break
}
}
}
var juniorPosition = Position.junior
juniorPosition.upgrade()
// MARK: - Protocol associated type in protocols (6 slide)
protocol ItemStoring {
associatedtype T
var items: [T] { get set }
mutating func add(item: T)
}
extension ItemStoring {
mutating func add(item: T) {
items.append(item)
}
}
struct NameDatabase: ItemStoring {
var items = [String]()
}
struct AgeDatabase: ItemStoring {
var items = [Int]()
}
var names = NameDatabase()
names.add(item: "James")
names.add(item: "Jess")
var ages = AgeDatabase()
ages.add(item: 23)
ages.add(item: 27)
//print(names)
//print(ages)
// MARK: - Subscript in protocols (7 slide)
protocol BoardType: class {
var width: Int { get }
var height: Int { get }
subscript(x: Int, y: Int) -> Int { get set }
}
class Board: BoardType {
let width: Int
let height: Int
var matrix: Array2D<Int>
init(width: Int, height: Int) {
self.width = width
self.height = height
matrix = Array2D<Int>(columns: width,
rows: height,
defaultValue: 0)
}
subscript(x: Int, y: Int) -> Int {
get { return matrix[x, y] }
set { matrix[x, y] = newValue }
}
}
class Array2D<T> {
var columns: Int
var rows: Int
var matrix: [T]
init(columns: Int, rows: Int, defaultValue: T) {
self.columns = columns
self.rows = rows
matrix = Array(repeating: defaultValue,
count: columns * rows)
}
subscript(x: Int, y: Int) -> T {
get { return matrix[columns * y + x] }
set { matrix[columns * y + x] = newValue }
}
func printArray() {
for (index, value) in matrix.enumerated() {
print("Value = \(value) at index \(index)")
}
}
}
let board = Board(width: 2, height: 3)
board[1, 1] = 10
//board.matrix.printArray()
// MARK: - Init in protocols (8 slide)
protocol AgeInitProtocol {
init(age: Int)
}
class Soldier: AgeInitProtocol {
private let age: Int
required init(age: Int) {
self.age = age
}
}
final class FinalSoldier: AgeInitProtocol {
private let age: Int
init(age: Int) {
self.age = age
}
}
class Student {
init(age: Int) {
// init goes here
}
}
class EpamStudent: Student, AgeInitProtocol {
// 'required' due to AgeInitProtocol
// 'override' due to Student
required override init(age: Int) {
super.init(age: age)
// init goes here
}
}
protocol FailableAgeInitProtocol {
init?(age: Int)
}
class Adult: FailableAgeInitProtocol {
let age: Int
required init?(age: Int) {
guard age >= 18 else { return nil }
self.age = age
}
}
// MARK: - Delegates (9 slide)
protocol EngineDelegate {
func didStart()
func didFinish()
}
struct Engine {
var delegate: EngineDelegate
init(delegate: EngineDelegate) {
self.delegate = delegate
}
private func start() {
// your code goes here
delegate.didStart()
}
private func finish() {
// your code goes here
delegate.didFinish()
}
}
struct Car: EngineDelegate {
private var engine: Engine!
init() {
engine = Engine(delegate: self)
}
func didStart() {
// your code goes here
}
func didFinish() {
// your code goes here
}
}
let car = Car()
// MARK: - Default Implementations. Constraints. Protocol conformance with an extension. (10, 11 slide)
protocol CompanyProtocol {
var companyName: String { get }
}
extension CompanyProtocol {
var companyPhoneLabel: String {
"\(companyName) phone +1 999 ..."
}
}
protocol Printable {
func printValue()
}
extension Array: Printable where Element: Printable {
func printValue() {
for item in self {
item.printValue()
}
}
}
class Printer {
private let value: Int
init(_ value: Int) {
self.value = value
}
func printValue() {
print("Item is equal \(value)")
}
}
extension Printer: Printable {}
let arrayOfPrinters = [Printer(1), Printer(2), Printer(3)]
//arrayOfPrinters.printValue()
// MARK: - Protocol conformance examples. (Equatable, Hashable, Comparable) (12 slide)
struct EquatableStudent: Equatable {
var name: String
var age: Int
}
let student1 = EquatableStudent(name: "Ivan", age: 10)
let student2 = EquatableStudent(name: "Ivan", age: 10)
let isSameStudent = student1 == student2
class EquatableClassStudent {
var name: String
init(name: String) {
self.name = name
}
}
extension EquatableClassStudent: Equatable {
static func == (lhs: EquatableClassStudent, rhs: EquatableClassStudent) -> Bool {
return lhs.name == rhs.name
}
}
let epamStudent1 = EquatableClassStudent(name: "student")
let epamStudent2 = EquatableClassStudent(name: "student")
let isSameEpamStudent = epamStudent1 == epamStudent2
struct HashableStudent: Hashable {
var name: String
var age: Int
}
let hashableStudent1 = HashableStudent(name: "Ivan", age: 10)
hashableStudent1.hashValue
let hashableStudent2 = HashableStudent(name: "Viktor", age: 20)
hashableStudent2.hashValue
let arrayOfStudents = [hashableStudent1, hashableStudent2]
let dictOfStudents: [HashableStudent : String] = [hashableStudent1 : hashableStudent1.name,
hashableStudent2 : hashableStudent2.name]
let setOfStudents: Set = [hashableStudent1, hashableStudent2]
class HashableClassStudent {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
extension HashableClassStudent: Hashable {
static func == (lhs: HashableClassStudent, rhs: HashableClassStudent) -> Bool {
return lhs.name == rhs.name && lhs.age == rhs.age
}
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(age)
}
}
struct ComparableStudent {
var name: String
var age: Int
}
extension ComparableStudent: Comparable {
static func < (lhs: ComparableStudent, rhs: ComparableStudent) -> Bool {
lhs.age < rhs.age
}
}
let comparableStudent1 = ComparableStudent(name: "Ivan", age: 10)
let comparableStudent2 = ComparableStudent(name: "Viktor", age: 20)
let isStudent1Younger = comparableStudent1 < comparableStudent2
let isStudent2Younger = comparableStudent1 > comparableStudent2
let isStudentsSameAge = comparableStudent1 == comparableStudent2
// MARK: - Protocols as Types. Collections of Protocol Types. (13 slide)
protocol PhoneProcessor {
func run()
}
class Phone {
var processor: PhoneProcessor
init(processor: PhoneProcessor) {
self.processor = processor
processor.run()
}
}
class IntelProcessor {
func runIntelCore() { }
}
extension IntelProcessor: PhoneProcessor {
func run() {
runIntelCore()
}
}
class AppleProcessor {
func runAppleCore() { }
}
extension AppleProcessor: PhoneProcessor {
func run() {
runAppleCore()
}
}
let phoneProcessors: [PhoneProcessor] = [AppleProcessor(), IntelProcessor()]
for processor in phoneProcessors {
processor.run()
}
let objects: [Any] = [AppleProcessor(), IntelProcessor()]
for object in objects where object is PhoneProcessor {
(object as? PhoneProcessor)?.run()
}
// MARK: - Protocol Inheritance. Multiple protocols. (14 slide)
protocol CallProtocol {
func phoneCallStarted()
}
protocol SmartFunctionsProtocol {
func voiceDetected()
}
protocol SmartphoneProtocol: CallProtocol, SmartFunctionsProtocol { }
func takeSmartphone(_ smartphone: SmartphoneProtocol) {}
//protocol AppleSmartphoneProtocol: SmartphoneProtocol {}
//func takeSmartphone(_ smartphone: CallProtocol & SmartFunctionsProtocol) {}
typealias Smartphone = CallProtocol & SmartFunctionsProtocol
func takeSmartphone(_ smartphone: Smartphone) {}
//MARK: - Task
protocol TaskProtocol {}
struct SomeStruct: TaskProtocol {}
extension SomeStruct {
func printSomething() {
print("SomeStruct")
}
}
extension TaskProtocol {
func printSomething() {
print("SomeProtocol")
}
}
let someStruct = SomeStruct()
let someProtocol: TaskProtocol = someStruct
//someStruct.printSomething()
//someProtocol.printSomething()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment