Skip to content

Instantly share code, notes, and snippets.

@foxicode
foxicode / UIView+removeAllSubviews.swift
Created July 29, 2023 13:04
UIView removeAllSubviews Swift extension
public extension UIView {
func removeAllSubviews() {
let subviews = self.subviews
subviews.forEach {
$0.removeFromSuperview()
}
}
}
@foxicode
foxicode / UIView+forceLayout.swift
Created July 29, 2023 13:03
UIView forceLayout Swift extension
public extension UIView {
func forceLayout() {
setNeedsLayout()
layoutIfNeeded()
}
}
@foxicode
foxicode / DateFormatter+init.swift
Created July 29, 2023 13:02
DateFormatter custom constructor in Swift
public extension DateFormatter {
convenience init(dateFormat: String, locale: Locale) {
self.init()
self.dateFormat = dateFormat
self.locale = locale
}
}
@foxicode
foxicode / Int+asString.swift
Last active July 29, 2023 13:07
Int asString/toString Swift extension
public extension Int {
var asString: String {
"\(self)"
}
func toString() -> String {
"\(self)"
}
}
@foxicode
foxicode / existential.swift
Created February 15, 2023 21:02
Existential Any
import Foundation
protocol User: Identifiable {
var firstName: String { get set }
var lastName: String { get set }
}
func printUserName(_ user: any User) {
print("\(user.firstName) \(user.lastName)")
}
@foxicode
foxicode / keyPaths.swift
Created February 15, 2023 17:31
Swift keypaths
import Foundation
struct Item {
var name: String
var price: Int
}
extension Array {
func map<Value>(_ keyPath: KeyPath<Element, Value>) -> [Value] {
map { $0[keyPath: keyPath] }
@foxicode
foxicode / staticProtocolFuncs.swift
Created February 15, 2023 16:50
Protocols with static functions
import Foundation
protocol Hero {
static func weapon() -> String
static func fight()
}
extension Hero {
static func fight() {
print("Fighting with... \(weapon())")
@foxicode
foxicode / SwitchCaseWhere.swift
Created February 6, 2023 20:15
Switch - case - where construction
let point1 = (1.5, 0.5)
let point2 = (1.0, 0.0)
let point3 = (0.5, 0.5)
for point in [point1, point2, point3] {
switch point {
case let (x, y) where pow(x, 2) + pow(y, 2) < 1.0:
print("Point \(x), \(y) is inside the circle")
case let (x, y) where pow(x, 2) + pow(y, 2) == 1.0:
@foxicode
foxicode / Swizzling.swift
Created February 6, 2023 19:54
Swizzling in Swift
import UIKit
extension UIViewController {
@objc func altViewDidAppear(_ animated: Bool) {
print("View did appear - \(type(of: self))")
altViewDidAppear(animated)
}
static func swizzle() {
let originalSelector = #selector(UIViewController.viewDidAppear(_:))
@foxicode
foxicode / AssociatedTypes.swift
Created February 6, 2023 19:20
Associated types in Swift
protocol PItemCollection {
associatedtype ItemType
var items: [ItemType] { get set }
mutating func add(item: ItemType)
mutating func clear()
}
extension PItemCollection {
mutating func add(item: ItemType) {