Skip to content

Instantly share code, notes, and snippets.

func fetchBook(id identifier: String) async throws -> GoogleBook {
var components = URLComponents(string: "https://www.googleapis.com/books/v1/volumes")
components?.queryItems = [URLQueryItem(name: "q", value: "{" + identifier + "}")]
guard let url = components?.url else { throw URLError(.badURL) }
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(GoogleBook.self, from: data)
}
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
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? {
// CircleView.h
//
// Created by Robert Ryan on 4/24/21.
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
IB_DESIGNABLE
@interface CircleView : UIView
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 `!`
// The following results in thread explosion:
for idx in 0..<10_000 {
concurrentQueue.async(group: group) {
self.something.n += idx
}
}
// We would instead do
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
}
}
}
class A {
private var b = B(0)
private let lock = NSLock()
deinit {
NotificationCenter.default.removeObserver(self)
}
func changeB(_ i: Int) {
synchronized { b = B(i) }
// 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`
public class B {
private var lock = NSLock()
private var a: A? = nil
public func setA() {
lock.synchronized {
a = A(0)
}
}