Skip to content

Instantly share code, notes, and snippets.

import Foundation
import UIKit
extension Double {
func formatElevation() -> (AttributedString, AttributedString) {
let measurement = Measurement(value: self, unit: Locale.current.usesMetricSystem ? UnitLength.meters : UnitLength.feet)
var resultString = measurement.formatted(.measurement(width: .narrow, usage: .road, numberFormatStyle: .number).attributed)
let unitContainer = AttributeContainer.measurement(.unit)
@lahariganti
lahariganti / asynctosync.swift
Created September 28, 2021 12:40
AsyncSequence to Sequence
extension AsyncSequence {
func collect() async rethrows -> [Element] {
try await reduce(into: [Element]()) { $0.append($1) }
}
}
import SwiftUI
struct RemoteImage: View {
private enum LoadState {
case loading, success, failure
}
private class Loader: ObservableObject {
var data = Data()
var state = LoadState.loading
import Foundation
struct KeychainWrapperError: Error {
var message: String?
var type: KeychainErrorType
enum KeychainErrorType {
case badData
case servicesError
case itemNotFound
import CoreData
public struct CoreDataContextObserverState: OptionSet {
 public let rawValue: Int
 public init(rawValue: Int) { self.rawValue = rawValue }
  
 public static let inserted = CoreDataContextObserverState(rawValue: 1 << 0)
 public static let updated = CoreDataContextObserverState(rawValue: 1 << 1)
 public static let deleted = CoreDataContextObserverState(rawValue: 1 << 2)
 public static let refreshed = CoreDataContextObserverState(rawValue: 1 << 3)
// Swift doesn’t yet provide a way to restrict <ProtocolType> to protocols only
// One could pass a concrete class type instead of a protocol for ProtocolType
// However, we'll use only a protocol; hence, the generic type is named as ProtocolType instead of just Type
public class MulticastDelegate<ProtocolType> {
// MARK: - DelegateWrapper
/// Used to wrap delegate objects as a weak property
/// so that the multicast delegate can hold onto strong wrapper instances, instead of the delegates directly that is
private class DelegateWrapper {
weak var delegate: AnyObject?
init(_ delegate: AnyObject) {
extension View {
func debug() -> Self {
print(Mirror(reflecting: self).subjectType)
return self
}
}
protocol Storyboarded {
static func instantiate() -> Self
}
extension Storyboarded where Self: UIViewController {
static func instantiate() -> Self {
let id = String(describing: self)
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
return storyboard.instantiateViewController(identifier: id) as! Self
}
@IBDesignable final class UILocalizedLabel: UILabel {
@IBInspectable var tableName: String? {
didSet {
guard let tableName = tableName else { return }
text = text?.localized(tableName: tableName)
}
}
}