Skip to main content

Optionals? in Swift

 


“You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.”

This quote is from  “The Swift Programming Language (Swift 5.2)”.  Books

And that’s the easiest and perfect explanation in my opinion. Here I’m gonna explain those a little bit deeper. Grab a cup of coffee and enjoy ☕️

Optional is a type of some value that can provide but doesn’t have to. For that, you use a “?” at the end of the type. For example:

And now we created a String which is optional

Maybe let’s see some more complex examples where we can actually see how it works.

Here we are creating some server response Integer with a value of 404. Then we want to print to the console this value. We can see that the console is telling us that this value is optional. But when we set the "serverResponseCode" to nil, then we get nil. It might be a scenario where we want to get some data from the user and we won’t get that for some reason. If we won’t use an optional here then our code for sure will crash.

Let’s edit our code a little bit:

Now I used “!” to unwrap the value of serverResponseCode and it forced me to get a value. But if I would use “!” in the second print then Xcode will give an error because there is no value.

But there is another way to fix this.

You can use “??” to put other values if there is no value from the user. This print checks if there is a value of serverResponseCode then it will print it, otherwise, we will get 500 as a result of this line.

It is really easy if you practice optionals a little. They are very useful when you want to avoid errors and crashes 😄

Comments

Popular posts from this blog

How to build FAQ Chatbot on Dialogflow?

  After Google I/O I’m inspired and excited to try new APIs and learn new stuff from Google. This time I decided to try Dialogflow and build a Flutter Chatbot app that will answer some frequently asked questions about Dialogflow. This time I want to be focused more on Dialogflow rather than Flutter. Firstly, go to  Dialogflow ES console , create a new Agent, specify the agent’s name, choose English as a language and click “Create”. As you created a new agent go to setting and enable beta features and APIs and Save. Now let’s model our Dialogflow agent When you create a new Dialogflow agent, two default intents will be created automatically. The  Default Welcome Intent  is the first flow you get to when you start a conversation with the agent. The  Default Fallback Intent  is the flow you’ll get once the agent can’t understand you or can not match intent with what you just said. Click  Intents > Default Welcome Intent Scroll down to  Responses ....

Vertex AI – One AI platform, every ML tool you need

  This year on Google I/O (Google’s Developer conference) Google presented a new platform that unites all ML tools. Vertex AI brings together the Google Cloud services for building ML under one, unified UI and API. There are many benefits to using Vertex AI. You can train models without code, with minimal expertise required, and take advantage of AutoML to build models in less time. Also, Vertex AI’s custom model tooling supports advanced ML coding, with nearly 80% fewer lines of code required to train a model with custom libraries than competitive platforms. Google Vertex AI logo You can use Vertex AI to manage the following stages in the ML workflow: Define and upload a dataset. Train an ML model on your data: Train model Evaluate model accuracy Tune hyperparameters (custom training only) Upload and store your model in Vertex AI. Deploy your trained model and get an endpoint for serving predictions. Send prediction requests to your endpoint. Specify a prediction traffic...

Flutter 2 is here! What’s new?

  Flutter 2 is finally released. And it has a bunch of new stuff! As my core tech for this year is Flutter and automation (wait for it) I will write about it a lot! Here I want just to start the journey and show you the coolest news in Flutter 2 Web support Flutter’s web support has transitioned from beta to the stable channel. With this initial stable release, Flutter pushes the reusability of code to another level with the support of the web platform. So now when you create a Flutter app that is stable, the web is just another device target for your app. Find more details about this stable release in  Flutter’s web support blog post . Desktop The ReorderableListView now has grab handles for easy drag ’n’ drop with a mouse In this release, It was announced that Flutter’s desktop support is available in the stable channel under an early release flag. What this means is that we’re ready for you to give it a try as a deployment target for your Flutter apps: you can think of it a...