Skip to content

Instantly share code, notes, and snippets.

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)
}
}
class CustomAnnotation: MKPointAnnotation, Codable {
var imageName: String?
enum CodingKeys: String, CodingKey {
case latitude, longitude, title, subtitle, imageName
}
override init() {
super.init()
}
class CustomAnnotationView: MKAnnotationView {
override var annotation: MKAnnotation? { didSet { update(for: annotation) } }
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
canShowCallout = true
update(for: annotation)
}
override func prepareForReuse() {
/// Suspendable Task
///
/// This provides an interface by which one can write code that can periodically call
/// `waitIfSuspended`, to achieve a block of code that can be suspended.
///
/// Usage:
///
/// ```
/// let item = SuspendableTask { task in
/// for i in 0 ..< 1_000_000 {
extension Sequence where Element: FloatingPoint {
func mean() -> Element {
var count = 0
var sum: Element = 0
for element in self {
sum += element
count += 1
}
return sum / Element(count)