3 hours ago · 7 min read1421 words · Tech · hide · 0 comments

The concept of optionals has been a core part of Swift since the very beginning, and it’s incredibly rare to come across a Swift code base that doesn’t use optional values one way or another.However, despite both being so commonly used, and conceptually simple (an optional either contains a value, or it doesn’t), optionals have quite a few interesting features that go quite far beyond simple unwrapping using statements like if let or guard let. So let’s explore some of those features, shall we?Taking valuesSometimes, when handling an optional value, we want to immediately reset it back to nil when we’re done, effectively extracting (or taking) the inner value that the optional might contain.For example, within the following TextViewModel we apply a text suggestion that the user has accepted, and then set the suggestion property back to nil in order to reset our view model’s state:@MainActor struct TextViewModel { var text: String private(set) var suggestion: String? mutating func…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.