2022-01-01から1年間の記事一覧

Kotlin Unwrap an Optional Variable

val name: String? = "Cecil" name?.let { println(it) } ?: run { println("name is null") }

StoryBoardでSwiftUIをプレビューする

import SwiftUI import PlaygroundSupport struct ContentView: View { var body: some View { Text("Hello World") } } PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())

Programmatic Navigation Link

struct ViewA: View { @State private var isShowingViewB = false var body: some View { VStack { Button("Show View B") { isShowingViewB = true } NavigationLink( isActive: $isShowingViewB, destination: { ViewB() }, label: { EmptyView() } ) } }…

Dictionaryのキー存在しない時デフォルトバリューを提供する

let dic = ["dog": 1, "cat": 2] print(dic["chicken", default: 0]) // outputは0

SwiftのDataをKotlinのByteArrayに変換

KMM

extension Data { func toKotlinByteArray() -> KotlinByteArray { let byteArray = [UInt8](self) let kotlinByteArray = KotlinByteArray(size: Int32(byteArray.count)) for (i, byte) in byteArray.enumerated() { kotlinByteArray.set(index: Int32(i),…

Indices

let array = ["A", "B", "C"] for i in array.indices { print(i, array[i]) } equals let array = ["A", "B", "C"] for i in 0..

フォント追加

ステップ1 ステップ2 現在使えるフォントを確認する: for family in UIFont.familyNames.sorted() { let names = UIFont.fontNames(forFamilyName: family) print("Family: \(family) Font names: \(names)") }

Terminalの小技

Mac

実行を中止:Ctrl + C 入力行を削除:Ctrl + U 入力行の最後の単語を削除:Ctrl + W

Array(repeating, count)の罠

Array(repeating, count)はクラスを作成の時には使えない。 例えばArray(repeating: UIView(frame: .zero), count: 5)を書いた時実に作ったViewは一つだけ。五つのポインターは同じViewに指しているだけ。 正しいやり方は(0...4).map { _ in UIView(frame: .…

画面半分表示のModal View

iOS 15+では、新しいSafariブックマークのような画面半分表示のModal Viewが作れるようになりました。 let modalVC = ModalViewController() let modalNC = UINavigationController(rootViewController: modalVC) if #available(iOS 15.0, *) { if let sheet…

Content Hugging PriorityとContent Compression Resistance Priority

Content Hugging Priority:二つのコンテンツが並んで、十分なスペースがある場合、そのpriority高いやつはもっとタイトな形式で表示する。 例:textAのContent Hugging PriorityはtextBより大きい場合: Content Compression Resistance Priority:二つのコ…

frameとbounds

frameはsuperViewに対する位置、x, yはsuperViewによって変わる。 boundsはview自身に対する位置、x, yは常に0。 だからviewAのsubView viewBを作って、viewBはviewAを完全重合したい場合、viewB.frame = viewA.boundと書く。 因みに、viewを移動したり変形…

UIKitでStoryboardなしのアプリを作る

XcodeでUIKitのアプリを作成する。 Main.storyboardを削除する。 ProjectファイルのTarget -> General -> Deployment Info -> Main Interfaceを空欄にする。 Info.plist -> Application Scene Manifest -> Scene Configuration -> Application Session Role …

実用的なString Extension

SwiftのStringは色々な考慮上、便利なSubstring方法を提供されていない。LeetCodeをやる時Stringの問題が合うとかなり面倒くさい。下記のextensionをコピペーすれば大変助かる。 extension StringProtocol { subscript(_ offset: Int) -> Element { self[ind…

??の実行順序について

LeetCodeをやっている時バグを遭遇した。 dic[a] = dic[a] ?? 0 + 1 のようなコードを書いた時、dic[a]は常に1になってしまう。 原因は0 + 1はいつも先に実行される。 だから上記にコードは下記のように書かないといけない: dic[a] = (dic[a] ?? 0) + 1