Skip to content

Instantly share code, notes, and snippets.

View josippetric's full-sized avatar

Josip Petric josippetric

  • Zagreb, Croatia
View GitHub Profile
@josippetric
josippetric / WeakRefVirtualProxy.swift
Created August 24, 2023 12:17
Weak Reference Virtual Proxy
private final class WeakRefVirtualProxy<T: AnyObject> {
private weak var object: T?
init(object: T) {
self.object = object
}
}
extension WeakRefVirtualProxy: ConformingProtocol where T: ConformingProtocol {
func methodFromProtocol(aBoolProperty: Bool) {
@josippetric
josippetric / SwiftUIHelpers.swift
Last active March 31, 2023 07:38
SwiftUI Helpers
import SwiftUI
// Overload that allows some bindings to be optional. E.g. having an optional
// property bound to the TextField
// TextField("", text: $optionalProperty ?? "default value")
func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {
Binding(
get: { lhs.wrappedValue ?? rhs },
set: { lhs.wrappedValue = $0 }
extension Date {
var age: Int {
get {
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: self, to: Date())
return ageComponents.year ?? 0
}
}
}
@josippetric
josippetric / String+Localization.swift
Created March 28, 2023 07:34
String Localization Helper
extension String {
var localized: String {
return NSLocalizedString(self, comment: "")
}
func localized(comment: String) -> String {
return NSLocalizedString(self, comment: comment)
}
@josippetric
josippetric / AttributeConstructor.swift
Last active March 28, 2023 07:33
Swift Attributed String Construction Helpers
import UIKit
public enum AttributeConstructor {
public enum Attribute {
case lineHeight(CGFloat)
case lineHeightMultiple(CGFloat)
case alignment(NSTextAlignment)
case font(UIFont)
case kern(CGFloat)
case color(UIColor)
@josippetric
josippetric / Storyboarded.swift
Last active June 18, 2020 09:16
Storyboarded - Protocol to create ViewControllers from a storyboard
import UIKit
protocol Storyboarded {
static func instantiate(storyboardName: String?) -> Self
}
extension Storyboarded where Self: UIViewController {
static func instantiate(storyboardName: String?) -> Self {
// this pulls out "MyApp.MyViewController"
let fullName = NSStringFromClass(self)