Skip to content

Instantly share code, notes, and snippets.

View SpeechRecognizer.swift
let recognizer = SFSpeechRecognizer()
weak var task: SFSpeechRecognitionTask? // note weak reference, as the recognition task keeps strong reference for us while the task is underway
deinit {
task?.cancel() // if still running by the time we deallocate, stop it
}
func startRecognition(of fileURL: URL) {
task?.cancel() // if prior task running, stop it
View Image.swift
struct Images {
static func minus(pointSize: CGFloat? = nil) -> UIImage? {
image(named: "minus", pointSize: pointSize)
}
static func trash(pointSize: CGFloat? = nil) -> UIImage? {
image(named: "trash", pointSize: pointSize)
}
private static func image(named name: String, pointSize: CGFloat? = nil) -> UIImage? {
View CircleView.m
// CircleView.h
//
// Created by Robert Ryan on 4/24/21.
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
IB_DESIGNABLE
@interface CircleView : UIView
View Fetch.swift
func fetchData(symbol: String, completion: @escaping (Result<[StockPrice], Error>) -> Void) { // if you have compilation error here, try `Swift.Result<[StockPrice], Error>` instead
let url = URL(string: "https://google.com")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let object = ["symbol": symbol]
request.httpBody = try! JSONEncoder().encode(object) // or wrap this in `do`-`catch` block and use `try` without the `!`
View ThreadExplosion.swift
// The following results in thread explosion:
for idx in 0..<10_000 {
concurrentQueue.async(group: group) {
self.something.n += idx
}
}
// We would instead do
View SwiftUIExample.swift
class ModelTest: ObservableObject {
@Published var strings = [String]()
func update() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
print("now")
self?.strings = ["test"] // the update, DOES trigger an update of the view
}
}
}
View Synchronization.swift
class A {
private var b = B(0)
private let lock = NSLock()
deinit {
NotificationCenter.default.removeObserver(self)
}
func changeB(_ i: Int) {
synchronized { b = B(i) }
View InvoiceItem.h
// InvoiceLine.h
@import Foundation;
NS_ASSUME_NONNULL_BEGIN
@interface InvoiceItem : NSObject
@property (nonatomic, copy, nullable) NSString *title;
@property (nonatomic, copy, nullable) NSString *itemDescription; // because `description` has special meaning in `NSObject`, we’ll call this `itemDescription`
View NSLockingExample.swift
public class B {
private var lock = NSLock()
private var a: A? = nil
public func setA() {
lock.synchronized {
a = A(0)
}
}
View EncodableAnnotation.swift
class CustomAnnotation: MKPointAnnotation, Codable {
var imageName: String?
enum CodingKeys: String, CodingKey {
case latitude, longitude, title, subtitle, imageName
}
override init() {
super.init()
}