Skip to content

Instantly share code, notes, and snippets.

View Agarunov's full-sized avatar

Anton Agarunov Agarunov

View GitHub Profile
@Agarunov
Agarunov / type_erasure.swift
Last active November 10, 2021 15:12
Swift Type Erasure example
//: Playground - noun: a place where people can play
protocol ObjectMapper {
associatedtype SourceType
associatedtype ResultType
func map(_ object: SourceType) -> ResultType
struct Point: Hashable {
let x: Float
let y: Float
}
let p1 = Point(x: 0.0, y: 0.0)
let p2 = Point(x: 1.0, y: 1.0)
p1 == p2 // false
class Department { }
protocol Employee {
// warning: 'weak' should not be applied to a property declaration in a protocol
// and will be disallowed in future versions
weak var department: Department? { get }
}
// Declared inside framework
struct Point: Hashable {
let x: Float
let y: Float
init(x: Float, y: Float) {
self.x = x
self.y = y
}
}
#if canImport(UIKit)
// UIKit is available!
import UIKit
#endif
// Swift 4.1
#if targetEnvironment(simulator)
// Simulator!
#endif
// Swift 4.0
#if (arch(i386) || arch(x86_64)) && os(iOS)
// Simulator!
#else
// Device!
let friends = ["Ross", nil, "Joey", "Chandler"]
// Swift 4.0
let array1 = friends.flatMap { $0 } // ["Ross", "Joey", "Chandler"]
// Swift 4.1
let array2 = friends.compactMap { $0 } // ["Ross", "Joey", "Chandler"]
let string = "Hello, World!"
let keyPath = \String.[string.startIndex]
string[keyPath: keyPath]
struct Person: Codable {
let firstName: String
let lastName: String
}
let jsonData = """
{
"first_name": "John",
"last_name": "Watson"
}
extension Array: Equatable where Element: Equatable {
static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool {
// do stuff
}
}