Skip to main content

Posts

Showing posts with the label Library

Swift Optionals under the hood

In Swift, an Optional is a way to say “this value might be there, or it might be missing.” We use ? to show that a value is optional, like: var name: String? But what is really happening behind the scenes? What an Optional Really Is Inside Swift, an Optional is just a simple enum with two cases: enum Optional<Wrapped> { case none // no value case some(Wrapped) // has a value } That’s all an Optional is! So when you write: var age: Int? Swift actually thinks: var age: Optional<Int> The ? is only a shortcut for us. Why Optionals Feel Special Even though Optionals are simple, Swift gives them extra features: if let and guard let value ?? defaultValue value! for force unwrap a?.b?.c for optional chaining These special features work only with Swift’s built-in Optional. How Swift Stores Optionals Swift stores Optionals in a smart way: Many Optionals take no extra memory compared to the normal value. Swift uses unused bits or adds a small...

Benefits of Swift Testing over XCTest

If you’ve been building apps in Swift for a while, you’ve probably spent some time writing tests with  XCTest . It’s been the default testing framework on Apple platforms for years, and while it does the job, it often feels… a little clunky. Now enter Swift Testing — a newer, more modern testing framework that’s part of the Swift open-source project. The difference is immediately noticeable. Writing tests with Swift Testing feels like writing Swift code, not fighting a bunch of boilerplate. Here are some of the reasons why many developers are starting to prefer Swift Testing over XCTest: 1. The Syntax Just Flows Better In XCTest, you’re constantly reaching for XCTAssertEqual , XCTAssertTrue , XCTAssertNil , and so on. Each one has its own function, and you need to remember which is which. In Swift Testing, you simply use #expect with plain Swift expressions: #expect(result == 42) Compare that to: XCTAssertEqual(result, 42) Not a huge difference in one line, but when you multiply ...

Pocket guide to iOS app development enthusiasts

I would like to share all possible channels & resources that helps to pitch in iOS development. I'm sure existing iOS ninjas who are already consuming those in one or other ways. Before listing my points - we all know it's most important to keep updated techs and trends. Many cases I have seen some of the channels & connections helped developers to get their new jobs or app contracts. 1. Apple's Official Developer guide. Apple Documentation  is the first go over for all references.  Swift.org for Swift Language starting point. WWDC Videos (& New app launched as well) 2. Social Media Groups - Fast & easy way to connect with iOS community. Facebook Group   Twitter Lists for iOS handles 3. Slack workspaces - A sweet hub of all iOS developers connected by channels. ios-developers.slack.com (Suggested) 4. Online Courses   - Gives opportunity to learn and be certified developers. Udemy AppBrewery  Alison ( and more ) 5...

Backing multiple iOS versions

A latest iOS version update can cover ~85% of iPhone users which is significant compared to a newly released Android running just ~0.1% of devices. ( @StatistaCharts collected on September 2018 - iOS 11 vs Android Pie). If your application matters for the rest ~15% of “genuine” iOS users, then you have to spend extra time to support. Why does it matters ? Giving uniform user experience irrespective of iOS version and device factors - will give bonus market space for the sales. Essentially it will boost your revenue and popularity of the application. Deployment Target vs Base SDK Before heading to solution, we have to understand Xcode settings for Deployment Target and Base SDK.  A deployment target refers to the oldest version of iOS that is capable of running your project. To change your deployment target, open up your project file in Xcode and check the setting under Build Settings -> Deployment. Base SDK refers to the newest version of iOS that is capable of runn...

Storyboard vs XIB vs Custom UI Code

Have you ever felt difficulty while choosing between Storyboard and XIB or even going for Custom code? Let’s make it easier from this short article. As we know, Storyboard introduced in iOS 5 and it consists of several ViewControllers, whereas XIB (previously NIB) files can consist of only one controller scene. Even custom codes can do all UI actions of such as positioning or animations..etc without help of any GUI tools.  Further, we may not need to stick with only one of above options. We can have one or combinations of three as per the requirement. Pros of Storyboard: As its name says, we can visualize entire scene in a single shot. On the Storyboard file, we can configure the flow between pages directly by using segue. Segues takes care most of UI configurations. Reduces boilerplate code needed to pop, push, present and dismiss view controllers. When storyboard makes sense? A set of views say for example: Authentications (Login/Registration page), Wi...

Implementing autocompletion OTP field in iOS

Long waiting is over. !!  iOS 12 brings Autofill for OTP text field which is close to Android provided a decade back. Previously in iOS we used to toggle between OTP text screen and message inbox.  Which was hard to remember and time consuming resulting a bad user experience. Personally, I have been asked from the client/customer couple of times to implement autocompletion for OTP field and took me a lot of time to convey that it is not possible in iOS. Why Autofill was not possible previously?  We all know that Apple gives at most care for user privacy. When we see iOS architecture, each individual app is like a separate island. There is no inter-app bridge between apps (exception for Keychain and URLSchemes APIs which gives very limited scope). Thus we cannot read message content from inbox. Where to start Autofilling? First of all, the target SMS need to have the OTP Code with prefix string "Code" or "Passcode"on its message content. Beware of OTP c...

Static Vs Dynamic libraries in iOS

A library is a collection of resources and the code itself, compiled for one or more architectures. Apple provides 2 types of library architectures that behaves differently upon building our app. Static libraries (*.a) :  When the app launches Static libraries loaded into address space for future use. They become part of the executable, and are statically linked to client apps. Thus, it (especially large executable libraries) makes apps slower to load and run, even launch time of the apps. Apple shown the architecture of static libraries as below : Dynamic libraries (*.dylib) :  With dynamic libraries, the app loads code into its address space when it’s actually needed, either at launch time or at runtime. The libraries are not part of the executable file. Thus decreases the memory footprint for your app. Clearly dynamic frameworks has got more advantages over static frameworks. Notably, it is available for iOS 8 and above. Apple shown the architecture...

Language Server Protocol (LSP) for Swift

You might already heard “ Apple announced LSP support for Swift ”. This is overwhelming decision by Apple because it’s a great step towards openness from it’s ‘monopoly game’. You can check complete official announcement here by Argyrios Kyrtzidis . What exactly LSP and How it works ? This Post from NSHipster by Matt explains how it works and what are the benefits out of the LSP support. In short, LSP will enable Swift development other than Xcode with below seamless integrated features - Autocompletion Jump to Definition Syntax highlighting Tooltips Automatic formatting and many for editor features. Any editor (say Visual Studio) to understand Swift, it requires Swift package to be integrated. Thus, SourceKit-LSP (Still under development) comes into play. This open source project got contribution from large group of developers and releasing very soon. Later we can easily integrate Swift into any editing tool with the help of any package manager (NodeJS prefer...

Stored Properties vs Computed Properties

We will start with simple a property which can be defined as below : var firstValue : Int let length : Int = 22 We can see it's not defined inside any closure, (A Closure "{ }" is meant for Classes, Structures or Enumerations) Stored Properties are those properties kept inside Classes and Structures. (not enums) . So, it will be always instance of classes or structures. Here is 2 more examples  : struct FixedLengthRange { var firstValue : Int let length : Int } class FixedLengthRange { var firstValue : Int let length : Int } Computed properties are those properties which do not store values, instead it gives getter and optional setter methods to access those property values. struct Circle {   var rad = 0   let pi = 3.14   var area : Float    {      get {        return rad * rad * pi          }   ...

Popular posts from this blog

Implementing autocompletion OTP field in iOS

Long waiting is over. !!  iOS 12 brings Autofill for OTP text field which is close to Android provided a decade back. Previously in iOS we used to toggle between OTP text screen and message inbox.  Which was hard to remember and time consuming resulting a bad user experience. Personally, I have been asked from the client/customer couple of times to implement autocompletion for OTP field and took me a lot of time to convey that it is not possible in iOS. Why Autofill was not possible previously?  We all know that Apple gives at most care for user privacy. When we see iOS architecture, each individual app is like a separate island. There is no inter-app bridge between apps (exception for Keychain and URLSchemes APIs which gives very limited scope). Thus we cannot read message content from inbox. Where to start Autofilling? First of all, the target SMS need to have the OTP Code with prefix string "Code" or "Passcode"on its message content. Beware of OTP c...

Animating label text update - choosing a better way

Recently I published a countdown app .  At one point of development - I have to show a timer on a UILabel which ticks on each seconds. As usual I started  setting text to a label object - self .timerLabel.text = someString Easy piece of cake right !?   But wait ... it won't take much user attention when timer ticks on every seconds. So I decided to make use of a simple animation while label gets text update. I found there are dozens of ways to animate a label. In this short article, I listed 3 best way you can animate text on a label. ( Spoiler Alert 👀- I decided to go with 3rd option)  1. Fade In - Fade out animation : CATransition class has got transition type `fade`. With timing function of CATransition - I was able to see the below result. let animation: CATransition = CATransition () animation.timingFunction = CAMediaTimingFunction (name: CAMediaTimingFunctionName .easeInEaseOut) animation.type = CATransitionType .fade animation.subtype = C...

Cached Async Image in SwiftUI

 SwiftUI’s AsyncImage is handy, but every time your view appears, it refetches the image—leading to flicker, delays, and unnecessary network use. What if you could fetch once, then reuse instantly? That's exactly what the Cached Async Image  delivers: a memory-powered caching layer that keeps SwiftUI image loading smooth, snappy, and resilient. First a simple in-memory cache without disk persistence. This will be thread-safe and auto-purges under memory pressure. A Singleton wrapping NSCache for URL → UIImage caching as follows : final class ImageCache {   static let shared = ImageCache()   private init() {}   private let cache = NSCache<NSURL, UIImage>()   func image(for url: URL) -> UIImage? {     cache.object(forKey: url as NSURL)   }   func insertImage(_ image: UIImage?, for url: URL) {     guard let image else { return }     cache.setObject(image, forKey: url as NSURL)   }   func clearAll() { ...

Prevent Navigationbar or Tabbar overlapping Subview - solved for Card view

Recently, I started with a Card view added as a subview of UIView in a view-controller. When a view controller created along subviews, it tends to use entire screen bounds and also slips behind Tab bar or Navigation bar. In my current situation, it's second case. Casually new iOS developers will write a patch by additional value for coordinate y and subtracting bar height from its size. A lot of them posted in SO threads too : How to prevent UINavigationBar from covering top of view? View got hidden below UINavigationBar iOS 7 Navigation Bar covers some part of view at Top So, how I got solved ? self.edgesForExtendedLayout = [] This  will avoid all subviews in a view controller get behind any bars. Read full apple  documentation on here. Full Source code below :  //Simple view controller where its view layed-out as a card. class WidgetCardViewController : UIViewController { var containerView = UIView () //MARK:- View Controller Life Cyc...

UICollectionViewCell shows with wrong size on First time - Solved

We commonly use Collection view where its cell size calculated run time. The flow layout delegate is responsible to return individual cell sizes. BUT in most of the cases, delegate method `collectionView: layout sizeForItem:` expects cell size too early. Before generating actual cell size. extension YourViewController : UICollectionViewDelegateFlowLayout { func collectionView ( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize (width: externalWidth, height: externalHeight) } } For instance, if a cell size depends on external view and its frame is not yet ready - results with wrong (or outdated) cell size. Typically happens for the first time view controller laid out all views. You can find similar queries in StackOverflow community : Collection view sizeForItemNotWorking UICollectionViewCell content wrong size on first load How to refresh UICollec...