[Swift] I already have a lot of information, but I tried to summarize the cast (as, as !, as?) In my own way.

What is a type cast?

** Cast ** refers to treating variables and constants as more specific and general-purpose types. For example, it means to treat a variable that was Any type as String type, and conversely to treat String type as Any type.

Cast type

There are two types of cast, upcast and downcast. The difference between upcast and downcast is whether you treat it as a more general type or a concrete type.

What is upcast

Use upcast to treat it as a more general value (wider group).

Use as when dealing with upcasts. Now let's write the code.

.swift


let string: String = "sample" //String type
let any: Any = string as Any  //Upcast from String type to Any type

In this way ** value you want to upcast as type ** to upcast You can upcast by writing in the format.

What is downcast

Downcast refers to treating it as a more specific type. This is not always the case with downcasts. Includes the possibility of failure. So let's understand that the grammar is also premised on including failures.

There are two ways to write a downcast, using as? Or as!.

Downcast using as?

Now let's write the code. The way to write using as? is as follows.

.swift


let any: Any = "sample" as Any
let string = any as? String //Optional("sample")
let int = any as? Int //nil

The third line of the above example tries to downcast to an Int type, but fails because "sample" cannot be an Int type. In that case the value is nil.

The feature of as? Is that it becomes nil when it fails in this way. Along with that, if you look at the second line, this is a successful downcast to the String type, but the value is an optional type of the String type. This can fail, so the result is optional. (Optional type means to allow nil in a nutshell)

Downcasting using as? In this way will result in nil if the result is optional and fails.

Downcast summary using as?

① The result will be an optional type
② If it fails, the result will be nil.

Downcast using as!

The downcast using as! is written as follows.

.swift


let any: Any = "sample" as Any
let string = any as! String //"sample"
let int = any as! Int //Run-time error

The writing method itself is not so different from the case of as ?, but the result is different.

If the second line is as ?, the optional type is now the String type. In addition, there is a run-time error on the third line.

For those who know the optional type, it may have been roughly considered, but when using as !, the result is forcibly unwrapped, and instead of the result not being an optional type, at runtime if it fails. An error will occur and the app will crash. ** Downcasting using as! Is called forced casting. ** **

Downcast summary using as?

① The result is not optional
(2) If it fails, a run-time error will occur.

Should I use as? Or as!

I've been doing a downcast method using as? And as!.

Instead of being safe, you have to write what to do if it fails. On the other hand, as! Risks an error at runtime instead of having to write what to do if it fails.

It can be said that both have advantages and disadvantages, but personally, I think it is better to use as ?, which is basically safe.

As a dangerous pattern, I tried pressing [Fix] and it was solved, so it's okay! It is a pattern that causes a run-time error when executed. If you've read this far, you'll probably understand why it's not good, but be aware that using as! In this way tends to result in unstable code.

Summary

I would like to introduce the articles that I referred to when posting this article. https://fukatsu.tech/swift-cast

This time, I summarized about type cast. Typecasting is a basic part of swift, but I think it is necessary to understand it clearly because it is easy to encounter unexpected errors if you handle it without understanding it, or to fall into the state of writing it for the time being.

So, this time, in order to deepen my own learning, I organized and posted it while referring to other articles. Please refer to it!

Recommended Posts

[Swift] I already have a lot of information, but I tried to summarize the cast (as, as !, as?) In my own way.
I tried to summarize object orientation in my own way.
A super beginner has completed the Spring introductory book, so I will summarize it in my own way
I tried to summarize the state transition of docker
I tried to summarize the basics of kotlin and java
[Swift] I tried to implement the function of the vending machine
I tried to summarize the basic grammar of Ruby briefly
I tried to make a client of RESAS-API in Java
When I switched to IntelliJ, I got a lot of differences in the encoding of the properties file.
[For Swift beginners] I tried to summarize the messy layout cycle of ViewController and View
I tried to summarize the words that I often see in docker-compose.yml
I tried to illuminate the Christmas tree in a life game
I tried to summarize the methods of Java String and StringBuilder
I tried to make a sample program using the problem of database specialist in Domain Driven Design
I tried to make a parent class of a value object in Ruby
I tried to summarize the key points of gRPC design and development
I thought about the best way to create a ValueObject in Ruby
I tried to make full use of the CPU core in Ruby
[Ruby] I tried to summarize the methods that frequently appear in paiza
[Ruby] I tried to summarize the methods that frequently appear in paiza ②
I tried to summarize the methods used
I tried to summarize the Stream API
Since the unit test of the PJ I was in charge of was a hell picture, I will publish my own guide (?)
What I tried when I wanted to get all the fields of a bean
How to get the ID of a user authenticated with Firebase in Swift
I tried to organize the session in Rails
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
I tried to summarize the points to consider when acquiring location information with the iOS application ③
I tried to create a log reproduction script at the time of apt install
I tried to summarize the points to consider when acquiring location information with the iOS application ①
I tried to summarize the points to consider when acquiring location information with the iOS application ②
[Rails] I want to display the link destination of link_to in a separate tab
I tried to organize the cases used in programming
I tried to decorate the simple calendar a little
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to implement the Euclidean algorithm in Java
I finished watching The Rose of Versailles, so I tried to reproduce the ending song in Java
I tried to make the sample application into a microservice according to the idea of the book "Microservice Architecture".
[Rails 6.0, Docker] I tried to summarize the Docker environment construction and commands necessary to create a portfolio
I tried to develop the cache function of Application Container Cloud Service in the local environment
A story that I realized that I had to study as an engineer in the first place
I tried using the GitHub repository as a library server
Port C code with a lot of typecasts to Swift
I tried JAX-RS and made a note of the procedure
How to get the longest information from Twitter as of 12/12/2016
I tried to convert a string to a LocalDate type in Java
I tried to build the environment of WSL2 + Docker + VSCode
I tried to implement a buggy web application in Kotlin
I tried validation to unify the way hashtags are written
[Controller] I want to retrieve the numerical value of a specific column from the DB (my memo)
I tried to express the result of before and after of Date class with a number line
I tried to make the "Select File" button of the sample application created in the Rails tutorial cool
I tried to make a machine learning application with Dash (+ Docker) part2 ~ Basic way of writing Dash ~
I tried to take a look at the flow of Android development environment construction with Android Studio
When I tried to run my own service, it failed, so I screwed it into the task scheduler