Converting Your iOS Application to Android: Part 1

For anyone who noticed – I’ve been quite quiet on the blog front for a couple of years – one reason is I’ve become a father! It turns out being a dad takes up a lot of your time!

Another reason is I’ve been working on converting an app from iOS to Android, and re-learning Android on the way. I decided to write a 3 part series on this, and it has just been published on the blog at – see link here.

Here’s part 1 of the series for you to check out now:


Converting Your iOS Application to Android: Part 1

One of the biggest catches of building applications with native tools is they only work on one platform, and migrating an application takes time. After eight years on the iOS App Store, 250,000 downloads and many user requests for an Android version, I finally decided to migrate my most popular application, Subtitles Viewer, to Android. Here is some of what I learned on the journey.

First things first – why bother? If you have an iOS application that works fine, why put in all the work to convert your iOS application to Android?

Why convert your iOS application to Android?

Currently, iOS has just 27% of the global smartphone market, while almost all the rest are Android based (72%). That adds up to about 3 billion (that’s billion with a ‘b’!) active Android smartphone users that are not able to access your application. In the US, the story is a little different, with iPhones actually leading Android 55% to 44%. However – even if your market is focused purely on the States, you are still turning away nearly half of your potential customers at the door.

The story isn’t quite so simple though – even though Android outnumbers iOS smartphones 3 to 1, iOS users are much more likely to spend their cash on applications than Android users. In fact, your application installed on 1,000 iOS devices will earn about 4.5 times more on average than if it were installed on 1,000 Android devices. If you’re looking to maximize revenue, whether through application or in-app purchases, having an iOS application is obviously a very important part of your business strategy. However, if you’re reading this article, you most likely already have an iOS application, and are questioning whether it would be worth building an Android equivalent. And though each application installed onto a specific Android device is likely to generate significantly less revenue, Android is still an important feature of generating application related income, due to the sheer numbers of Android devices. In 2021, iOS applications earned 63% of total global mobile application revenue. This means that if you decide to not migrate your iOS application to Android you will be missing out on almost 37% of your potential income.

So far we’ve looked at revenue, but what about costs? As you probably are aware, if you would like to earn income from application sales on an Apple device, you will need to be part of the Apple Developer Program, which costs US$99 annually. Google, on the other hand, only charges you a one-off registration fee of US$25. Both companies also keep a percentage of your royalties. Apple keeps 30% of the income your application generates, unless you qualify for their small business program, which reduces Apple’s percentage of your income to 15%. Android takes a similar percentage royalty to Apple, taking 15% of your application’s income for the first million dollars. After your application has generated more than one million dollars, then Android adjusts their royalties to 30%. If that detail becomes relevant to your situation, I believe kudos is in order.

Considerations when Converting your iOS Application to Android

On the one hand developing for all of these Android devices does mean many more potential users of your application, but on the other hand you will need to take extra care in ensuring your application works on the vast array of different Android devices. Even if you consider all iPhones Apple have ever released, at the time of writing you only reach 34 different devices. Compare that with Android – Wikipedia keeps a list of all Android smartphones ever released, and at the time of writing the list numbers greater than 1,400. Of course you won’t expect your application to work on early Android devices but even just including devices since 2020 adds up to nearly 500 devices. That’s 500 devices with diverse specs, memory, speed, screen types and resolution that you’ll most likely want your application to work on.

Working in iOS, you’ll of course be accustomed to working with devices built just by Apple, with a familiar look and feel. Android, on the other hand appears on phones and tablets built by a wide range of brands – the same Wikipedia list above lists 73 unique Android brands, many which even have their own custom firmware built on top of the Android system.

While all iOS applications are distributed via the App Store, Android applications in Android are generally distributed via the Google Play Store. That said, some brands, such as Samsung or Amazon, integrate their own proprietary application store either alongside or instead of the Google Play Store. If for example, you want owners of Amazon Fire devices to be able to use your application, you will need to submit it to the Amazon Appstore.

When designing your application for iOS, you no doubt would be familiar with the App Store Review guidelines. This describes all of the guidelines that your application must comply with to be successfully accepted to the App Store. Android has an equivalent set of guidelines for submitting to Google Play, which you can access at the Google Play Policy Center. These guidelines have many similarities with Apple’s, restricting developers from publishing inappropriate content, infringing intellectual property, transparent handling of user data etc. Of course, if you are to submit your application to third party app stores such as Amazon Appstore, this introduces yet another set of guidelines that you must adhere to.

Another document which I’m sure you’re familiar with is Apple’s Human Interface Guidelines, which provides you with recommendations to follow to be consistent with Apple’s design aesthetic. Android has similar guidelines, called the Material Design Guidelines, which have actually recently been updated for Android 12 (released October 2021), called Material Design 3. This is where you’ll see more differentiation between Android and iOS. There are different naming conventions, standard fonts, and styles of navigation. In iOS, custom views such as buttons, switches, labels, sliders and pickers are called controls, while in Android these are called material components. You’ll find many Android material components have a different look and feel to their equivalent (if there is an equivalent) in iOS. In iOS applications for example, you are likely to move between tabs at the bottom of the screen – in Android, tabs appear near the top of the screen, and if you would like tabs at the bottom of the screen you will need to use what’s called a bottom navigation bar. It would be a good idea to have a look at Android’s Material Design Guidelines and devise a plan on how to convert your application’s interface from an iOS aesthetic to Android.

If you don’t have an Android device, it’s worth considering purchasing one, and familiarizing yourself with the Android approach to user experience. There are also certain features that the Android emulator (the equivalent of Xcode’s simulator) are not able to reproduce, and to test them properly you will need a device. Also, nothing beats actually experiencing how your application operates on a physical device with a touch screen – it’s here, where you’re using the touch screen and experiencing your application on a real device, where you’ll often discover issues you might not have noticed in the emulator.

After weighing up the pros and cons of making the transition to iOS and considering all of these factors, I decided (admittedly after several years of procrastination!) that it was time to migrate Subtitles Viewer from iOS to Android.

In part 2 of this series, I’ll be doing a deep dive into similarities and differences in developing an application for Android vs iOS.

This post was originally posted on, link here.

Posted in Android, iOS, Java, Swift

Holy cow – You can preview UIKit code live in Xcode!

Now that SwiftUI is feeling more and more established since WWDC 2020, I’m in the process of getting properly acquainted with it. In my exploring I discovered something actually more relevant to UIKit that blew me away. (and it’s been around since 2019!)

So you can use SwiftUI code to preview UIKit objects live – UIViewControllers or UIViews – from within Xcode 😲, in the canvas.

Here’s how – first UIViewController:

Let’s say you have a UIViewController subclass ViewController.

  • Step 1: In the Storyboard (let’s assume Main) give your view controller a storyboard ID. Let’s say ‘ViewController’.
  • Step 2: Head over to your ViewController.swift file. Make the ViewController class final:
final class ViewController: UIViewController {
  • Step 3: Import SwiftUI:
import SwiftUI
  • Step 4: Again, in your ViewController.swift file, create an extension for ViewController, implementing the  UIViewControllerRepresentable protocol, with its two required functions:
extension TermsViewController: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> ViewController {
    func updateUIViewController(_ uiViewController: ViewController, context: Context) {

We can ignore the updateUIViewController function as this is used by a SwiftUI parent to update the model data of the view controller.

  • Step 5: Return our View Controller from the makeUIViewController function. We can do this with the UIStoryboard.instantiateViewController function.
func makeUIViewController(context: Context) -> ViewController {
  UIStoryboard(name: "Main", bundle: nil)
    withIdentifier: "ViewController") as! ViewController
  • Step 6: Set up a preview provider that returns your View Controller as a preview:
struct ViewControllerPreviews: PreviewProvider {
  static var previews: some View {

Just like that, BAM, the canvas appears to the right of the ViewController, and within it, your view controller as it would appear in the simulator. But that’s not all – press the play button to the bottom right of the ViewController, and a live version of your view controller will actually run, right there in a panel next to your code, just as if it were SwiftUI. Holy cow!

Oh – and one more thing – if you want to preview a UIView rather than a UIViewController it’s pretty straightforward – just extend your custom view class with UIViewRepresentable rather than UIViewControllerRepresentable!


Tagged with:
Posted in Swift, SwiftUI

Making a simple toggle button with UIButton

It’s actually pretty straightforward to turn a UIButton into a toggle button. (checkbox, switch, whatever you prefer to call it!)

We can make use of the isSelected property that UIButton inherits from UIControl. All we need to do is connect a ‘Touch Up Inside’ action to the UIButton, that toggles this property:

@IBAction func toggleButton(_ sender: UIButton) {

Pretty easy right? Just like that, our button now toggles between the ‘Default’ and ‘Selected’ Control States. We can customize how these states look in the attributes inspector for the button.

Here I have customized a button to display either a tick or cross, depending on whether it’s selected, using SFSymbols ‘’ and ‘’:

This seems to work pretty well, except for one minor detail. When the user has their finger down on the button, the button defaults to the ‘Default’ state (although darker). This works ok for the ‘unselected’ state, but doesn’t look quite right for the ‘selected’ state:

No Highlighted state selected.

How can we modify this state? If you open the ‘State Config’ combo box, you’ll find another state called ‘Highlighted’:

In UIButton this state refers to the state the button is in while the user’s finger is on it. Great! So we can modify the Image for this state too in the Attributes Inspector. Here I’m setting the image for the ‘Highlighted’ state to ‘’:

Testing this out on the app, we see that this didn’t actually help us much! Sure, our ‘Default’ state has a neat ‘Highlighted’ state now, but our ‘Selected’ state still is defaulting to the ‘Default’ state when the user holds their finger down on the button:

What we need is to define the state for both ‘Selected’ AND ‘Highlighted’. Unfortunately that isn’t possible in the storyboard, but fortunately for us, we can do it in code. Just set up an @IBOutlet for your button, and then set the button’s image for this state in the viewDidLoad method. Here I am setting the image to ‘’ if the button is selected and the user holds their finger down on the button:

@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
  button.setImage(UIImage(systemName: ""), 
                  for: [.highlighted, .selected])

Finally! If we test the app now the button’s states should now be much more intuitive:


So — here again are the steps to creating a simple toggle button:

  1. Customize the button(for example, its image) in the attributes inspector of the storyboard for three states — ‘Default’ (off), ‘Highlighted’ (over) and ‘Selected’ (on).
  2. Connect the button to an IBOutlet so that you can set up a fourth state (a combination of ‘Highlighted’ and ‘Selected’) in the viewDidLoad method:
button.setImage(UIImage(systemName: ""), 
                  for: [.highlighted, .selected])

3. Connect the button to an IBAction that actually performs the toggling:

@IBAction func toggleButton(_ sender: UIButton) {

That’s it! Your button should work.

A reusable toggle button subclass

Of course, if you prefer you could set up a subclass of UIButton that handles the toggle operation for you:

import UIKit
class ToggleButton: UIButton {
  @IBInspectable var highlightedSelectedImage:UIImage?
  override func awakeFromNib() {
    self.addTarget(self, action: #selector(btnClicked(_:)), 
                   for: .touchUpInside)
                  for: [.highlighted, .selected])
  @objc func btnClicked (_ sender:UIButton) {

This subclass contains an inspectable property highlightedSelectedImage that you can use to specify the image to display in the elusive fourth state (‘Selected’ and ‘Highlighted’) that is otherwise not available in the attributes inspector.

Connecting your button to this subclass in the identity inspector, you can now completely set up your toggle button in the storyboard. Hooray!👍


Tagged with: ,
Posted in Swift

Tiling a background image – sans code!

I recently wrote an article on a simple custom UIView class you can use to tile an image. Unfortunately – this doesn’t help us in a LaunchScreen, where custom classes are not allowed. Fortunately – there’s another way to tile an image, it’s pretty straightforward, and it doesn’t require a single line of code!

Step 1 – Bring in your image to tile into the Assets Catalog, then select Editor > Show Slicing.Screenshot 2019-11-12 14.51.47.png

Step 2 – The 1x, 2x and 3x options will disappear, and you will need to select Start Slicing.

Screenshot 2019-11-12 14.52.19.png

Step 3 – You will have the option to slice horizontally, vertically or both:

Screenshot 2019-11-12 14.52.27.png

Xcode will assume you want to slice the image in the center.

Screenshot 2019-11-12 14.52.32.png

This will stretch the center part of your image, something like this:

Screenshot 2019-11-12 15.03.47.png

This isn’t what you want!

Here are the defaults Xcode chose when I opted to slice my image: (you can find these in the Attributes Inspector for the image – and don’t forget, we’re still in the Assets Catalog)

Screenshot 2019-11-12 14.52.44.png

Step 4 – We need to set the Left, Right, Top and Bottom to 0, and the Width and Height of the Tiles to the width and height of the image. Something like this:

Screenshot 2019-11-12 14.53.05.png

Step 5 – Now, back in the Storyboard, we can add a UIImageView, and in the Attributes Inspector, make sure Content Mode is set to Scale To Fill:

Screenshot 2019-11-12 14.54.03.png

And there, like magic, the image in our image view will tile, and it works in the LaunchScreen storyboard too, hooray!

Screenshot 2019-11-12 14.54.08.png

Tagged with: ,
Posted in Swift

Tiled background image in custom UIView class

Sometimes you need a repeated or tiled image in your app, often for a background. Something like these rain-drops for example:

Here’s a simple UIView subclass that accepts an image parameter, and renders a repeated tiled image, even in the storyboard:

class TiledImageView:UIView {
@IBInspectable var image:UIImage?
override func draw(_ rect: CGRect) {
guard let image = image else {return}
UIColor(patternImage: image).setFill()
let path = UIBezierPath(rect: rect)

It creates a patterned image in a UIColor object, sets this as the current fill, and then fills the view’s rect with this color.

Here’s how it looks in the storyboard:

Tagged with: ,
Posted in Swift

Presentation Style default in iOS 13

This week is International Week of the Deaf, so to thank the community that have been a big part of my app Subtitles Viewer‘s success, Subtitles Viewer PRO is free for the whole week. Coincidentally, and perhaps unfortunately, iOS 13 is also brand spanking newly released this week, so just when the app is getting substantial downloads, some teething issues have presented themselves with the new release. Grrr…

Now I know Apple liked large navigation bars from iOS 11, but these navigation bars looked extra large. What’s worse, I found that after building the app in Xcode 11, when I swipe down, the whole app disappeared, leaving behind just the title screen!

Strange! I took a look at the good old capture view hierarchy and discovered a transition view peeking up above the navigation controller. Hmm, the plot thickens…

Screenshot 2019-09-26 16.33.48.png

What’s going on? It turns out this was all related to a change in default presentation style.

Blink and you’ll miss it – in the WWDC State of the Union 2019, this was announced:

Another component of iOS 13’s new look is cards. Since the original SDK, the default presentation style on iPhone has covered the full screen. We’re changing that default to a much more fluid card presentation. Cards provide a visual stack so you can see at a glance that you’re in a presentation. And even better, they’re dismissible with just a single downward swipe.

Screenshot 2019-09-26 23.22.05.png

So previously segues would always default to a presentation style of ‘Full screen’, exhibit a:

Now, presentations on the iPhone default to what Apple are calling ‘cards’, exhibit b:

Note that after presenting the view controller as a card, you can swipe it down to remove it.

In practice, what has happened is that the default presentation style is ‘automatic’ which in iOS 13 is interpreted by UIViewController as ‘Page Sheet’. The documentation for UIModalPresentationStyle.automatic describes this: “For most view controllers, UIKit maps this style to the UIModalPresentationStyle.pageSheet style”.

This new feature could work well in some UX design, but in Subtitles Viewer, when the intro animation is complete it automatically segues to the rest of the app. Swiping down to see the intro animation again was definitely unwanted in this case.

What to do about it? Turns out the solution is simple. If you select the presenting view controller in the storyboard and select Attributes Inspector, you’ll find the Presentation attribute is probably set to Automatic. Change this Full Screen, and you’re done, problem solved!


Tagged with: , ,
Posted in Swift

Property Wrappers and User Defaults

I love magical new features that help us abstract away boiler-plate code and let us focus on the unique features of our apps. Property wrappers is such a feature, and seriously – it just feels like magic!


Let’s take a look at an example to see how property wrappers work.

User defaults: Level 1

A reminder, the simplest way user defaults would work is to first set up some sort of a key:

enum Keys { //enum to prevent instantiation
  static let beenHereBefore = "Been Here Before"

You could then use this to store or retrieve the user default:

//Retrieve user default:
if !UserDefaults.standard.bool(forKey: Keys.beenHereBefore) {
  //Onboarding could go here for example
//Store user default:
UserDefaults.standard.set(true, forKey: Keys.beenHereBefore)

Great! But wouldn’t it be nicer if we could just set and retrieve the property without worrying about the underlying user defaults implementation?

User defaults: Level 2

Instead, let’s abstract away the User defaults code into a GlobalSettings type:

//Retrieve user default:
if !GlobalSettings.beenHereBefore {
  //Onboarding could go here for example
//Store user default:
GlobalSettings.beenHereBefore = true

Much more readable, right?

But of course, we now need to set up the GlobalSettings type:

enum GlobalSettings { //enum to prevent instantiation
    enum Keys {
        static let beenHereBefore = "Been Here Before"
    static var beenHereBefore:Bool {
        get {
            return UserDefaults.standard.bool(forKey: Keys.beenHereBefore)
        set {
            UserDefaults.standard.set(newValue, forKey: Keys.beenHereBefore)

Now that’s fine for one user default, but what if we have several? We would have to duplicate this code defining a key and setting and retrieving the UserDefaults for each property.
Could we abstract this code even further? Well, here’s where we can see the magic of property wrappers!

Screenshot 2019-09-02 21.01.33

User defaults: Boss Level! (using Property Wrappers)

A property wrapper is a special attribute you can create and apply to a property that automatically runs a bunch of code behind the scenes for the property.

Let’s move the User Defaults get and set code to a property wrapper.
*Disclaimer: the code for Persist is based on sample code in the Swift Evolution proposal for Property Wrappers, proposal 258.

Let’s give the property wrapper the name Persist:

struct Persist<T> {
  let key: String
  let defaultValue: T

  var wrappedValue: T {
    get {
      return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
    set {
      UserDefaults.standard.set(newValue, forKey: key)

To define the property wrapper we follow three essential steps:

1. Create a type (in this case, a struct). The name of our type becomes the name of the property wrapper.
2. Prefix the type with the @propertyWrapper attribute.
3. Include a ​wrappedValue property. In this case this a generic property wrapper, so the wrappedValue property is defined as a generic. To perform an action when this property is retrieved or stored, it is defined as a computed property with both a getter and a setter.

In this case, as UserDefaults needs a key to store and retrieve a property, a key property has been defined in the Persist struct.

As the property wrapper is defined as generic, it uses UserDefault‘s generic object method to retrieve a user default. As this method returns an optional, the Persist struct also defines a defaultValue property that will be returned if the value returned by the object method is nil.

Of course, as Persist is a struct, it doesn’t need an initializer specifically defined to intialize these two properties, as a memberwise initializer will be automatically generated.

Now, we can adjust our GlobalSettings type to use the property wrapper:

enum GlobalSettings {
  @Persist(key: "BeenHereBefore", defaultValue: false)
  static var beenHereBefore: Bool

Holy moly. You can see how much shorter the declaration of the beenHereBefore property is, now that all of the UserDefaults code has been abstracted to our custom property wrapper Persist.

All we did to add our custom property wrapper was to prefix a variable with an at symbol (@) followed by the name of the wrapper (Persist), followed by any initialization required.
Like magic, the property wrapper code we wrote will now execute for this variable!

We could easily add a bunch of user defaults to our GlobalSettings type, with minimal additional lines of code.

enum GlobalSettings {
  @Persist(key: "BeenHereBefore", defaultValue: false)
  static var beenHereBefore: Bool
  @Persist(key: "TopScore", defaultValue: 0)
  static var topScore: Int
  @Persist(key: "UserName", defaultValue: "Anon")
  static var userName: String

As all the code dealing with persisting data is now in our Persist property wrapper, if we wanted to make adjustments to how this works, we would only have to make this change in one place. Let’s say we change our mind and decide to use iCloud’s NSUbiquitousKeyStore container to persist our data, instead of UserDefaults. Making this change would be straight-forward:

struct Persist {
  let key: String
  let defaultValue: T

  var wrappedValue: T {
    get {
        return NSUbiquitousKeyValueStore.default.object(forKey: key) as? T ?? defaultValue
    set {
        NSUbiquitousKeyValueStore.default.set(newValue, forKey: key)

As I mentioned, you can read more about property wrappers in Swift Evolution proposal 258. You can also see more about it in WWDC video Modern Swift API Design. Just be cautious, back then wrappedValue was simply known as value. (it was renamed 8 days after the talk – ooh that would be frustrating!)

Enjoy playing with property wrappers, let me know what magical property wrappers you create!

Tagged with: ,
Posted in Swift

SF Symbols in iOS 13

I was playing with the amazing SwiftUI with Apple’s tutorials (stay tuned, I hope to write something on SwiftUI soon) when I noticed something interesting:

Screen Shot 2019-06-06 at 8.55.02 pm.png

Where does this “star.fill” come from, I wondered… There’s no “star.fill” in the asset catalog?! It turns out the clue was in the initializer parameter “systemName”.

So from iOS 13, UIImage can now be initialized with systemName, which generates a “system symbol image”.  What are these “system symbol images”? Well, Apple has provided a program called “SF Symbols” that lets you browse all 1,500+ of them! You can download the program at their Apple Design Resources page.

Screen Shot 2019-06-07 at 9.16.15 am.png

Here are just some of the SF Symbols!

And it couldn’t be easier to use:

Screen Shot 2019-06-06 at 11.33.39 pm.png

There is a WWDC session on SF symbols well worth checking out here. You’ll also find Apple’s guidelines for using SF Symbols in the Human Interface Guidelines here. You’ll also find guidance there for building your own SF Symbol, using the SF Symbols program.

In the SF Symbols program you’ll notice you can play with the weight and scale of the image. You’ll find an example of these in the Human Interface Guidelines:


You can adjust the weight and scale of the image, along with its pointSize, using a config property:

Screen Shot 2019-06-06 at 11.44.22 pm.png

It should be noted that pointSize refers to a typographical point size – the same point size a font uses – rather than points on the screen.

Why have both pointSize and scale, you might ask. Well, the scale property allows you to adjust the scale of a symbol in relation to the text around it without having to adjust the pointSize. Perhaps you might be lining up an image with a label, adding an image to a button, or even inserting an SF symbol in a string! It should be mentioned that inserting an SF symbol into a string isn’t working yet for the current beta of Xcode 11, but it sounds very promising, adjusting the style of the symbol to the text surrounding it!

Having point size available is great, but we generally try to avoid specifying a point size with text — instead we prefer to use text styles, such as Body, Headline, etc where possible to take advantage of dynamic type. This is possible with SF symbols too — instead of specifying the point size, you can create the config property using a text style, just as you might with a label or text field:

Screen Shot 2019-06-07 at 1.18.28 pm.png

By the way, so far we’ve been looking at how to add SF symbols in code. We also saw at the start of this post that you can also include SF symbols in SwiftUI views.You might be interested to know you can also add them in the storyboard:

Screen Shot 2019-06-07 at 12.08.55 pm.png

Of course, as we saw at the start of this post, you can also include SF symbols in SwiftUI views.

Well, that’s the basics – there’s a lot more to look at – such as alignment, automatic configuration based on size class, making your app with SF symbols compatible with devices with < iOS 13, and building your own SF symbols. Again, I recommend you check out the WWDC session on SF symbols here.

In conclusion I think this is a really welcome addition to Xcode/iOS – apps will have a more consistent look across iOS, and I think SF symbols should make life much easier for us – less time for example, taken up sourcing icons and finding (or designing) a variety of sizes and weights. What do you think?

Tagged with: , , , ,
Posted in Swift

Swift 5 – it’s alive!

its-alive.jpgIt’s been a couple of weeks now since Swift 5 has arrived, with a bunch of features, such as:

  • ABI stability
  • source compatibility
  • isMultiple – a fancy technique for checking if a number is a multiple of another number.
  • Dictionary compactMapValues – finally we can properly compactMap a dictionary!
  • Result type – handle results from aynchronous code in a much cleaner way.
  • Raw strings – again Swift has had some enhancement to handling Strings.
  • And more!

If you want to a refresher on one or more of these features, I go into them in detail in a new Medium post, you can check it out here.

Tagged with:
Posted in Swift

Optionals in Swift explained – with a cat in a box!

If you’ve come to Swift from a language that doesn’t use optionals, you might find the concept a little strange and the syntax unfamiliar at first. Sometimes it helps to learn the unfamiliar with something familiar – in my lightning tour of optionals, I explain optionals with a cat in a box!

So – imagine you have a box:


Inside the box you know you have one of two things – either no cat…


…or a cat!


What you have just imagined, is a Cat optional!


As you can see, you declare an optional with the data type of its contents (Cat in this example), followed by a question mark:

var cat:Cat?

But now that we have a Cat optional, how do we get at its contents – or put another way – how do we unwrap the box?

Check my lightning tour of Optionals to find out:

Tagged with:
Posted in Swift