Skip to content

Instantly share code, notes, and snippets.

https://open.spotify.com/playlist/5xdvmNizfHeCz8fVvaXL4F?si=1f_Q5o4KRh-63p-mwckUlg&dl_branch=1
@Thomvis
Thomvis / Migrated.swift
Last active October 30, 2024 07:43
An approach towards migrating properties in a Codable struct without having to write a custom Codable implementation
import Cocoa
// Say we have a Person model
enum V1 {
struct Person: Codable {
let name: String
var age: Int
}
}
let timer = Timer.publish(every: 1.0, on: RunLoop.main, in: .common)
.autoconnect()
.prepend(Date())
.map { $0.timeIntervalSince1970 }
.lane("shared timer")
.share()
.lane("timer")
timer
.sink { print($0) }.store(in: &cancellable)
struct ContentView: View {
var body: some View {
VStack(alignment: .customAlignment) {
HStack {
Text("100 m").font(Font.body.bold())
Text("Usain Bolt").setCustomAlignmentToLeading()
}
HStack {
Text("5 km").font(Font.body.bold())
Text("Joshua Cheptegei").setCustomAlignmentToLeading()
@Thomvis
Thomvis / NestedClosureWeakSelfRetainCycle.swift
Last active April 13, 2021 12:13
Capturing a weak reference to self in a nested closure could cause a retain cycle. `[weak self]` weakly captures self from the outer closure. Since the outer closure did not declare a weak reference to self, it will keep a strong one.
class ViewModel {
let intGetterGetter: () -> () -> Int?
var currentInt = 2
init() {
self.intGetterGetter = {
return { [weak self] in
return self?.currentInt
}
@Thomvis
Thomvis / onPreferenceChangeWorkAround.swift
Created February 6, 2020 13:17
It seems that `onPreferenceChange` is not always called. I have an override using `overlayPreferenceValue` and `View.id`. I suspect the fact this view is inside a `ScrollView` matters.
content
.onPreferenceChange(SizeKey.self, perform: { sizes in
// this is not always called
})
.overlayPreferenceValue(SizeKey.self) { sizes in
EmptyView().onAppear {
// this is called more reliably
// the view's id controls for which changes this is called
}.id(sizes.map { $0.width*1000+$0.height })
}
//
// ContentView.swift
// NavigationViewTest
//
// Created by Thomas Visser on 04/11/2019.
// Copyright © 2019 Thomas Visser. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var tab = 0
@State var selections: [Int:Int] = [:]
var body: some View {
ZStack {
TabView(selection: $tab) {
NavigationView {
PageView(n: 0, selections: $selections)
}.navigationViewStyle(StackNavigationViewStyle()).tabItem { Text("Pages") }.tag(0)
//
// ContentView.swift
// FlowLayoutST
//
// Created by Chris Eidhof on 22.08.19.
// Copyright © 2019 Chris Eidhof. All rights reserved.
//
import SwiftUI
struct FlowLayout {
@Thomvis
Thomvis / UIControlEventPublisher.swift
Last active July 4, 2019 09:01
UIControlEventPublisher.swift
class ActionTarget {
let handler: () -> Void
init(handler: @escaping () -> Void) {
self.handler = handler
}
@IBAction func handle() {
handler()
}