SwiftUI View and @FetchRequest predicate with variable that can change

had the same problem, and a comment of Brad Dillon showed the solution: var predicate:String var wordsRequest : FetchRequest<Word> var words : FetchedResults<Word>{wordsRequest.wrappedValue} init(predicate:String){ self.predicate = predicate self.wordsRequest = FetchRequest(entity: Word.entity(), sortDescriptors: [], predicate: NSPredicate(format: “%K == %@”, #keyPath(Word.character),predicate)) } in this example, you can modify the predicate in the initializer.

Saving CGImageRef to a png file?

Using CGImageDestination and passing kUTTypePNG is the correct approach. Here’s a quick snippet: @import MobileCoreServices; // or `@import CoreServices;` on Mac @import ImageIO; BOOL CGImageWriteToFile(CGImageRef image, NSString *path) { CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL); if (!destination) { NSLog(@”Failed to create CGImageDestination for %@”, path); return NO; } … Read more

Keep window always on top?

To change the window level you can’t do it inside viewDidload because view’s window property will always be nil there but it can be done overriding viewDidAppear method or any other method that runs after view is installed in a window (do not use it inside viewDidLoad): Swift 4 or later override func viewDidAppear() { … Read more

How to convert a decimal number to binary in Swift?

You can convert the decimal value to a human-readable binary representation using the String initializer that takes a radix parameter: let num = 22 let str = String(num, radix: 2) print(str) // prints “10110” If you wanted to, you could also pad it with any number of zeroes pretty easily as well: Swift 5 func … Read more

Providing a default value for an Optional in Swift?

Update Apple has now added a coalescing operator: var unwrappedValue = optionalValue ?? defaultValue The ternary operator is your friend in this case var unwrappedValue = optionalValue ? optionalValue! : defaultValue You could also provide your own extension for the Optional enum: extension Optional { func or(defaultValue: T) -> T { switch(self) { case .None: … Read more

Swift Alamofire: How to get the HTTP response status code

For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 4.0 / Alamofire >= 5.0 response.response?.statusCode More verbose example: Alamofire.request(urlString) .responseString { response in print(“Success: \(response.result.isSuccess)”) print(“Response String: \(response.result.value)”) var statusCode = response.response?.statusCode if let error = response.result.error as? AFError { statusCode = error._code // statusCode private switch error { case .invalidURL(let … Read more