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.
In addition, arc4 random()
has a return value of UInt32.
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
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.
Int()
is not a cast but an initializer call of type Int
.
as Int is the conversion process and Int(xxx) is the initialization process.
887 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
572 Understanding How to Configure Google API Key
599 GDB gets version error when attempting to debug with the Presense SDK (IDE)
609 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.