About the language specifications of the swift cast

Asked 2 years ago, Updated 2 years ago, 68 views

Please tell me the difference between as Int and Int().

If you use as Hoge when you cast with swift, it will be cast.
Also, Int() is recognized as a function that casts into Int.
I looked at Apple's official documentation, but I didn't really understand the difference between the two.

If you cast as Int and Int() with the code in the capture below, you can see that as Int is the only one. There will be an error.If you are unable to cast UInt32 to Int, you can also use Int() to
I think it's okay to get the same error, but considering that it doesn't, the behavior of both of them is
I think there is a difference.

In the first place, it is also a mystery that UInt32 cannot be cast into Int.
I would appreciate it if you could explain that as well.
Thank you.
Cast

In addition, arc4 random() has a return value of UInt32.

ios swift xcode

2022-09-29 21:42

3 Answers

as does ダウンdowncast 」.
Sample: (The first import foundation is required)

import Foundation

var myArray: [AnyObject] = ["Tomas", 24, 174.8]
let name = myArray[0] as String
letage=myArray[1] as Int
let height = myArray[2] as Float

AnyObject of type has an inheritance relation to String, Int, and Float, so it can be downcasted in as.There is no inheritance relationship between String, Int, and Float, so you cannot cast as.The same goes for Int32.

One more thing. You can also cast as between the type created in typealias and the original type.

typealias MyInt=Int

let value: MyInt=34
let value2 = value as Int
let value 3: Int=54
let value4 = value3 as MyInt


2022-09-29 21:42

The swift Type casting is the cast on the class hierarchy.
Int and UInt32 have no inheritance relationship and cannot be cast.

Type casting is a way to check the type of an instance, and/or to
treat that instance as if it is a different superclass or subclass
from somewhere else else in its own class hierarchy.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html

Int() is not a cast but an initializer call of type Int.


2022-09-29 21:42

as Int is the conversion process and Int(xxx) is the initialization process.


2022-09-29 21:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.