Skip to main content

iOS Coding Cheatsheet

This cheatsheet preserves the original Swift and SwiftUI snippets and comments; only Markdown headings and code fences were added for readability.

Property Observer: sanitize value on change

// Processing setting of a value

var email: String {
didSet {
guard email != oldValue {
return
}

email = email.trimmingCharacters(in: .whitespacesAndNewlines)
}
}

UserDefaults basics

let defaults = UserDefaults.standard
defaults.set("value", forKey: "someKey")
defaults.synchronize()

if let value = defaults.string(forKey: "someKey") {
// work with value
}

Text utilities

"Some text".lowercased(),
"Some text".uppercased(),
// capitalize every word
"Some text".capitalized(),

Use UIKit view inside SwiftUI

// To use UIKit in SwiftUI

struct MultiplierLabelView: some UIViewRepresentable {
var text: String

func makeUIView(context: Context) -> some UIView {
MultiplierUILabel()
}

func updateUIView(_ uiView: MultiplierUILabel, context: Context) {
uiView.text = text
}
}

List all available fonts (App Delegate)

// To get all available fonts to check names
// In App Delegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

UIFont.familyNames.forEach({ name in
for font_name in UIFont.fontNames(forFamilyName: name) {
print("\n\(font_name)")
}
})

return true
}

Debug view updates

// To debug views

struct SomeView: View {
let _ = Self._printChanges()

var body: some View {
Text("Hello")
}
}