I was investigating cast . I was allowed to ask.
let test2: String = "sample"
print ("type Of test2: \ (type (of: test2))")
let test1: Any = test2 as Any
print ("type Of test1: \ (type (of: test1))")
Here, all the print results will be "String" type.
If upcasting is being done, I think test1 will be any, but why is it still a String type ...?
-
Answer # 1
-
Answer # 2
It's written in the official document
If you don't understand the official document here, you can normally add a question.
Rather, comments are not searchable, so questions are buried even though they have been written."This type (of :) function can be used to find the dynamic type of a value, especially if the dynamic type is different from the static type. Compile-time value type.The dynamic type of the value is the actual type of the runtime value and may be a subtype of the concrete type. "
First of all, there is an explanation of the static type of the value, "It is a known compile-time value type." I don't know what this means. And as an explanation of dynamic types, there is "subtype of concrete type", but I don't know what it means
About static types (known compile-time types)"Known compile-time value types."
A type defined in the source code.
The dynamic type is the actual type at runtime.func printInfo (_ value: Any) { let t = type (of: value) print ("'\ (value)' of type '\ (t)'") } let count: Int = 5 printInfo (count) // '5' of type 'Int'
count is the static type Int.
The dynamic type is 5, so it is Int.I'm passing this count variable to the printInfo function
The static type of the dummy argument value in the printInfo function is Any.
And the dynamic type obtained with type (of :) is Int.In the questioner's code
let test2: String = "sample" print ("type Of test2: \ (type (of: test2))") let test1: Any = test2 as Any print ("type Of test1: \ (type (of: test1))")
The String of test2 and the Any part of test1 are static types."Subtypes of concrete types"
In short, it ’s a downcast.
The function argument is generic, so it's not possible to use Any, but I think the parent type is often defined (static type).
It means getting an inherited type (subtype) that is an actual instance, not the original type.Back to the original question
I think test1 will be any
The idea of becoming an Any is misunderstood, and it is correct to get the original type String.
Static? dynamic? It might be confusing, but in a simple example.
Because we defined "String" in the source, it does n’t mean the actual situation is String.
In the following, the character "String" does not appear, but since the actual condition of "sample" is String, the result of type (of :) is String.let test1: Any = "sample" print ("type Of test1: \ (type (of: test1))")
-
Answer # 3
Do you know that the type recognized by the compiler only changes?
Additional
(Note: The word label used in the explanation below is used for explanation, not a term commonly used in Swift)The compiler labels each variable/constant with a type label at compile time.
The compiler uses the labels to determine the methods and properties that can be used.let a = 0 let b = a as Any
, B as an entity remains Int, but the type as a label recognized by the compiler is Any.
So if you try to use Int methods and properties for b, it will result in a compile error.However, type (of :) looks at the entity, not the label, so it returns the Metatype of the entity.
-
Answer # 4
First, the type of the variable (or constant) and the type of the value contained in the variable may not always match.
With
For example, iflet a: Any = "text"
, the type ofa
is Any, but the actual value type isstring
, an upcast only allows the cast target to be used as a superclass, not something that rewrites the value itself.
So
let test1: Any = test2 as Any
Islet test1: Any = test2
It is the same as writing.Next about type (),
The type of the variable itself can be found by looking at the source code (= static), so there is no need to examine it, for example,string
type variables
variabletype isstring
.
The type of the value contained in the variable is not always determined by looking at the source code. Determined at runtime. (= Dynamic)
The type () function checks the dynamic type.
Bonus: Casting reference
type-casting-operator
Theasoperator performs a cast when it is known at compile time that the cast always succeeds, such as upcasting or bridging. variable. The following approaches are equivalent:
func f (_ any: Any) {print ("Function for Any")} func f (_ int: Int) {print ("Function for Int")} let x = 10 f (x) // Prints "Function for Int" let y: Any = x f (y) // Prints "Function for Any" f (x as Any) // Prints "Function for Any"
The
as
operator is used for casts that are known to succeed at compile time (eg upcast)Expression can be used as a supertype without intermediate variables (using upcast)
Related articles
- ios - about management and profitability of apps developed by receiving orders
- ios - about tap judgment of reality kit
- ios - about the method of passing values when transitioning with present modally
- ios - questions about masterdetail
- ios - about environment construction of application using arkit_plugin
- ios - about farebase user registration
- about os version upgrade support in ios apps
- about symbolicate (restore) of crash log due to rejection when applying for swift iosapp
- ios - about processing when data could not be obtained by api
- ios - questions about string manipulation
- ios - about the mechanism that can pass by value at the time of screen transition in segue
- ios - it is about line breaks when using uitextview wrapped in swift ui
- ios - [swift] about the header of tableview i want to prevent the header from following even if it scrolls ]
- ios - about some problems with http communication in monaca
- ios - questions about setting up a collectionview inside a tableview
- ios - about the relationship between swift's user default and the project
- ios - about deleting userdefaults and updating view in swiftui
- [swift] how to get the coordinates of a circle (round pot) with ios-charts
- ios - [swift] i want to get the coordinates of the textfield that i dragged and moved when the keyboard is displayed
- ios - xcode error "uilocalnotification" is abolished
- ios - change the number assigned to the day of the week when creating a calendar application in swift
- ios - i want to get the index number of the selected pin in the mkpointannotation array
- ios - i want to simplify the code for visualizing the swift game hp
- ios - [swift/cloudkit] how to update records in the background
- ios - i want to display it in the swift cell linked to the last name
- ios - questions about setting up a collectionview inside a tableview
- ios - delegate is always returned as nil
In PHP,
In this way, the variable type changes dynamically, and the entity (instance) also works as if it changes. I think aae_11 probably assumes this behavior.
Swift cannot do this. Swift casting is not a type conversion function like PHP casting. The statement
let test1: Any = test2 as Any
convertstest2
toAny
type and assigns it totest1
It is not.First, to change a type in Swift, you need to create a new type entity.
int1
below performs type conversion by creating a newInt
entity based onstring1
. I'm not casting. Attempting to cast with int2 will result in an error. Even betweenFloat
andDouble
cannot be converted by casting.So what is a Swift typecast? Excerpt of explanation
Interpretation: Typecasting is a function for examining the type of an entity and treating it as a superclass or subclass in the entity's class hierarchy. Implemented with
is
andas
operators.Swift casts can only be used between superclasses and subclasses. Attempting to convert to a different type will result in an error. Also, there is no type conversion function in the first place.
TheAny
type is very special, and any type can be cast to and fromAny
.The statement
let test1: Any = test2 as Any
treatstest2
as aAny
type and usesAny
type Assigning to a certaintest1
. The entity does not change at all. The only difference is the type of the variable referencing the entity.Swift does an implicit cast, so you only have to specify it explicitly when
Any
is involved, for exampleUserDefault
Use.If the stored "storedIntValue" key value is of type
Int
,a
andb
are the same. However, if it is not aInt
type,a
will have someInt
value, butb
Will crash because it fails to cast.Because it is dangerous, use
Any
only when the library requires it, and avoid using it yourself. Because it destroys the benefits offered by the type.