Skip to content

Instantly share code, notes, and snippets.

View inamiy's full-sized avatar

Yasuhiro Inami inamiy

View GitHub Profile
@inamiy
inamiy / iOS16-NavigationStack.swift
Last active June 12, 2022 06:55
iOS 16 NavigationStack binding + navigationDestination behavior (Xcode 14 Beta 1, Swift 5.7) https://twitter.com/inamiy/status/1535861181998862337
import SwiftUI
struct RootStringNavStack: View {
@State
var navigationPath: [String] = []
// For hook-printing.
var navigationPathBinding: Binding<[String]> {
.init(
get: { navigationPath },
@inamiy
inamiy / actor-custom-executor.swift
Last active April 13, 2022 03:05
Swift 5.5 Actor impl with stealing GlobalActor's Executors https://twitter.com/inamiy/status/1514076289443176453
import Foundation
import _Concurrency
actor SomeSystem {
nonisolated var unownedExecutor: UnownedSerialExecutor {
#if os(Linux)
MyActor.sharedUnownedExecutor
#else
MainActor.sharedUnownedExecutor
#endif
import Foundation
import _Concurrency
// https://twitter.com/inamiy/status/1506118628839546880
var f: () -> () = {}
var fSendable: @Sendable () -> () = {}
var fMain: @MainActor () -> () = {}
var fMainSendable: @MainActor @Sendable () -> () = {}
@rethrows
protocol P {
func foo() throws
}
struct S1: P {
func foo() {}
}
struct S2: P {
// Q. How to abstract Actor's impl into protocol?
// 1. Plain protocol + async methods
protocol MyProtocol
{
var foo: Int { get async }
func bar() async
}
/// `async` monad that wraps async function.
public struct Async<T>
{
public let run: () async -> T
}
// MARK: - Functor
extension Async
{
func asyncThrowsToAsyncResult<A, B>(_ f: @escaping (A) async throws -> B)
-> (A) async -> Result<B, Error>
{
{ a in
do {
return .success(try await f(a))
} catch {
return .failure(error)
}
}
@inamiy
inamiy / withTaskCancellationHandler.swift
Last active August 19, 2021 15:33
Swift async/await: Re-inventing URLSession's `func data(for:) async throws` https://twitter.com/inamiy/status/1428378193170288645
import Foundation
let url = URL(string: "https://httpbin.org/get")!
@main
struct Main {
static func main() async throws {
print("1")
let task1 = Task.init { () -> Data? in
import SwiftUI
extension View {
func pipe<R>(@ViewBuilder _ f: (Self) -> R) -> R {
f(self)
}
}
struct ContentView: View {
@State var flag: Bool = false
@inamiy
inamiy / flattened-to-tree.hs
Created May 15, 2021 12:52
Flattened to Tree structure
-- こういうフラットな配列から木構造を作るのってどうやったらいいんだろう?
-- https://twitter.com/suin/status/1390626013814476800
{-# LANGUAGE DeriveFunctor, UndecidableInstances, LambdaCase #-}
module Main where
import Data.Functor.Classes
import Data.List