How to deal with actor reentrancy in Swift

Issue #912 Perform check before and after suspension point actor Worker { var isDoing = false var toBeDone = Set<String>() func work(string: String) async { if isDoing { toBeDone.insert(string) return } isDoing = true await performHeavyWork(string: string) isDoing = false if let first = toBeDone.popFirst() { await work(string: first) } } private func performHeavyWork(string: String) async { try? await Task.sleep(nanoseconds: 5_000_000_000) print(string) } } func main() { let worker = Worker() Array(0 ....

May 5, 2023 路 1 min 路 Khoa Pham

How to run parallel Task with Swift concurrency

Issue #911 Make an parallelTask function that wraps TaskGroup public func parallelTask(@ParallelTaskBuilder builder: () -> [ParallelTaskBuilder.Work]) async { await withTaskGroup(of: Void.self) { group in for work in builder() { group.addTask { await work.value } } } } @resultBuilder public struct ParallelTaskBuilder { public typealias Work = Task<Void, Never> public static func buildExpression(_ expression: Work?) -> [Work] { if let expression = expression { return [expression] } return [] } public static func buildExpression(_ expression: Work) -> [Work] { [expression] } public static func buildExpression(_ expression: [Work]) -> [Work] { expression } public static func buildBlock(_ components: Work....

April 27, 2023 路 1 min 路 Khoa Pham

How to use Range and NSRange in Swift

Issue #910 Use one-sided range operator let string = "Hello world" string[string.startIndex...] // Hello world string[..<string.endIndex] // Hello world Substring let string = "Hello world" let range = string.startIndex ..< string.index(string.startIndex, offsetBy: 5) string[range] // Hello Convert to and from NSRange let string = "Hello world" let range = string.startIndex... let nsRange = NSRange(range, in: string) let regex = NSRegularExpression(pattern: pattern) let matches = regex.matches(in: string, range: nsRange) for match in matches { let range = Range(match....

March 12, 2023 路 1 min 路 Khoa Pham

How to handle status bar with custom overlay UIWindow

Issue #908 When we add another UIWindow, then its rootViewController will decide the style of the status bar, not the rootViewController of the keyWindow anymore childForStatusBarStyle The usual way to fix this is to defer the decision to the correct rootViewController, like in our HUDViewController class HUDViewController: UIViewController { override var childForStatusBarStyle: UIViewController? { let windows = view.window?.windowScene?.windows ?? [] for window in windows where window != self.view.window { return window....

November 22, 2022 路 2 min 路 Khoa Pham

How to use SwiftUI Charts

Issue #907 Read more

October 30, 2022 路 1 min 路 Khoa Pham

How to use actor in Swift concurrency

Issue #905 Protect mutable state with Swift actors Actor reentrancy Imagine we have two different concurrent tasks trying to fetch the same image at the same time. The first sees that there is no cache entry, proceeds to start downloading the image from the server, and then gets suspended because the download will take a while. While the first task is downloading the image, a new image might be deployed to the server under the same URL....

October 5, 2022 路 4 min 路 Khoa Pham

How Task use thread in Swift concurrency

Issue #904 Consider this code where we have an ObservableObject with fetch1 and async fetch2, and a fetch inside ContentView Here the observation in Xcode 14 ViewModel.fetch1: run on main thread ViewModel.fetch2: run on cooperative thread pool ContentView.fetch: run on main thread import SwiftUI import CoreData import Combine class ViewModel: ObservableObject { @Published var string = "" func fetch1() { let url = URL(string: "")! let data = try!...

October 4, 2022 路 4 min 路 Khoa Pham

How to show animated gif NSImage on Mac

Issue #903 let image = NSImage(contentsOf: url) let imageView = NSImageView(image: image) image.animates = true

September 25, 2022 路 1 min 路 Khoa Pham

How to find previous frontmost application in macOS

Issue #900 Listen to didActivateApplicationNotification and check that it is not our app NSWorkspace.shared.notificationCenter .publisher(for: NSWorkspace.didActivateApplicationNotification) .sink(receiveValue: { [weak self] note in guard let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication, app.bundleIdentifier != Bundle.main.bundleIdentifier else { return } self?.frontMostApp = app }) .store(in: &bag)

August 2, 2022 路 1 min 路 Khoa Pham

How to show view below title bar for macOS in SwiftUi

Issue #899 Use NSTitlebarAccessoryViewController var titleBarAccessoryVC: NSTitlebarAccessoryViewController { let vc = NSTitlebarAccessoryViewController() let view = HStack { Spacer() Button { } label: { Text("Save") } .buttonStyle(.borderedProminent) .controlSize(.large) } .padding(.horizontal) vc.view = NSHostingView(rootView: view) return vc } let window: NSWindow = ... window.addTitlebarAccessoryViewController(titleBarAccessoryVC)

July 30, 2022 路 1 min 路 Khoa Pham

How to drag using DragGesture in SwiftUI

Issue #898 Change element position using either offset or position, and use DragGesture Use GestureState to store the updating startDragLocation to keep the start location when drag begins, so we can add translation struct MoveModifier: ViewModifier { @Binding var position: CGPoint @GestureState private var startLocation: CGPoint? func body(content: Content) -> some View { content .gesture(gesture) } private var gesture: some Gesture { DragGesture() .onChanged { value in var position = startLocation ?...

July 28, 2022 路 1 min 路 Khoa Pham

How to pass FocusState binding in SwiftUI

Issue #896 Use underscore _focus we get access to underlying FocusState object, but underscore _ is private to a View hence can鈥檛 be used in extension If we want to pass FocusState to another View or in extension, we can pass its Binding enum FocusElement: Hashable { case name case email } struct ParentView: View { @FocusState var focus: FocusElement? var body: some View { ChildView1(focus: _focus) ChildView2(focus: $focus) } } struct ChildView1: View { @FocusState var focus: FocusElement?...

July 28, 2022 路 1 min 路 Khoa Pham

How to move reversed List in SwiftUI

Issue #895 Apply .move on reversed array List(selection: $viewModel.selectedBook) { ForEach(viewModel.books.reversed()) { book in BookCell(book: book) } .onMove { source, dest in var reversed = Array(viewModel.books.reversed()) reversed.move(fromOffsets: source, toOffset: dest) viewModel.books = reversed.reversed() } }

July 25, 2022 路 1 min 路 Khoa Pham

My favorite WWDC videos

Issue #891 WWDC18 Designing Fluid Interfaces Testing Tips & Tricks WWDC22 The craft of SwiftUI API design: Progressive disclosure Writing for interfaces Read more

June 10, 2022 路 1 min 路 Khoa Pham

WWDC swiftui-lounge

Issue #890 In WWDC21, WWDC22 Apple provide a Slack channel for people to interact with Apple engineers in digital lounges. Here I note down some interesting Q&As WWDC22 What鈥檚 the difference between a custom ViewModifier vs View extension Q: What鈥檚 the difference between a custom ViewModifier (without DynamicProperty) that uses some built-in modifiers in body(content:), and a custom View extension func that just use those built-in modifiers? Similarly, what鈥檚 the difference between a custom ViewModifier with some DynamicProperty and a custom View with some DynamicProperty (also has a @ViewBuilder content property to receive content to modify) ?...

June 10, 2022 路 32 min 路 Khoa Pham

What's new in SwiftUI iOS 16 at WWDC22

Issue #889 What鈥檚 new in SwiftUI New EnvironmentValues TextField inside Alert List uses UICollectionView See gist ButtonStyle composition Section("Hashtags") { VStack(alignment: .leading) { HStack { Toggle("#Swiftastic", isOn: $swiftastic) Toggle("#WWParty", isOn: $wwdcParty) } HStack { Toggle("#OffTheCharts", isOn: $offTheCharts) Toggle("#OneMoreThing", isOn: $oneMoreThing) } } .toggleStyle(.button) .buttonStyle(.bordered) } Customize Charts struct MonthlySalesChart: View { var body: some View { Chart(data, id: \.month) { BarMark( x: .value("Month", $0.month, unit: .month), y: .value("Sales", $0.sales) ) } ....

June 9, 2022 路 5 min 路 Khoa Pham

How to use any vs some in Swift

Issue #888 Embrace Swift generics This generic pattern is really common, so there鈥檚 a simpler way to express it. Instead of writing a type parameter explicitly, we can express this abstract type in terms of the protocol conformance by writing 鈥渟ome Animal鈥. The 鈥渟ome鈥 in 鈥渟ome Animal鈥 indicates that there is a specific type that you鈥檙e working with. func feed<A>(animal: A) where A: Animal {} func feed(animal: some Animal) An abstract type that represents a placeholder for a specific concrete type is called an opaque type....

June 8, 2022 路 5 min 路 Khoa Pham

How to use Swift

Issue #887 What鈥檚 new

June 7, 2022 路 1 min 路 Khoa Pham

How to use SwiftUI

Issue #886 SwiftUI iOS 16 SwiftUI SwiftUI practices 8 Common SwiftUI Mistakes 鈥 and how to fix them! 5 Steps to Better SwiftUI Views SwiftUI tips and tricks SwiftUI Tips Tips thread Quick Friday tips Reference

June 7, 2022 路 1 min 路 Khoa Pham

How to convert NSImage to PNG Data

Issue #885 Create NSBitmapImageRep with preferred size and draw NSImage onto that. Need to construct NSBitmapImageRep specifically instead of using convenient initializers like NSBitmapImageRep(data:), NSBitmapImageRep(cgImage:) to avoid device dependant resolution issue. extension NSImage { func pngData( size: CGSize, imageInterpolation: NSImageInterpolation = .high ) -> Data? { guard let bitmap = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bitmapFormat: [], bytesPerRow: 0, bitsPerPixel: 0 ) else { return nil } bitmap....

June 6, 2022 路 1 min 路 Khoa Pham