Arbitrary types, generics, and casts are also frequently used in development.
A. Any b. Any C. Any D. Any
Swift provides two special types: Any and AnyObject.
Any: Can represent Any type (enumerations, structs, classes, and even function types)
AnyObject: can stand for any class type (write after the protocol: AnyObject means that only the class complies with the protocol)
Example code 1:
class Person { }
var p: Any = 10
p = "idbeny"
p = Person()
Copy the code
It will not compile if the variable p is followed by a concrete type or if no type is written.
Example code two (holding an array of any type) :
Var data = [Any]() data.append(1) data.append(1.01) data.append(Person()) data.append("idbeny") data.append({ 10 })Copy the code
Example code 3:
protocol Runnable: AnyObject { }
class Person: Runnable {
}
Copy the code
- If the above example code three is used
struct
:
- To switch to
Any
Can be used normally:protocol Runnable: Any { } struct Person: Runnable { } Copy the code
Is, as? And the as! And as
Is is used to check whether the type is a certain type, and AS is used to perform type casting.
Example code 1 (use of IS) :
protocol Runnable { func run() } class Person { } class Student: Person, Runnable { func run() { print("Student run") } func study() { print("Student study") } } var stu: Any = 10 print(stu is Int) true print(stu is Double) false stu = "idbeny" print(stu is String) True stu = Student() print(stu is Person) // Print: true print(stu is Runnable) // print: trueCopy the code
Example code two (use of AS) :
(stu as? Student)? .study() // no output stu = Student() (stu as? Student)? .study() // Output: Student study(stu as! Student).study() // output: Student study(stu as? Student)? .run() // Output: Student runCopy the code
as?
: Converts to an optional typeas!
: cast type (error on failure)as
: must be able to use when the cast is successful.
Application Scenario 1 of as:
var data = [Any]()
data.append(Int("123") as Any)
Copy the code
Application Scenario 2 of as:
Var d = 10 as Double print(dCopy the code
X. elf, X. type and AnyClass
X. elf is a pointer to metadata, which holds type-specific information. AnyClass is the anyObject. Type Type, which represents any meta-type.
Example code 1: x. elf belongs to x. type. Person.self is similar to person. class in OC.
class Person {
}
var p = Person()
var pType: Person.Type = Person.self
Copy the code
Assembly analysis:
Person.self represents the first 8 bytes (metatype information address) of the instance object to which the pointer P points in heap space.
Example code 2:
class Person { }
class Student: Person { }
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
perType = Student.self
var anyType: AnyObject.Type = Person.self
anyType = Student.self
public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = Person.self
anyType2 = Student.self
Copy the code
A parent pointer can point to an instance of a subclass.
Example code 3:
Var per = Person() print(person.self == type(of: per)Copy the code
Type (of: per) essentially fetches out the first eight bytes of the object.
The application of meta-types
Example code 1:
class Animal {
required init() { }
}
class Cat: Animal { }
class Dog: Animal { }
class Pig: Animal { }
func create(_ clses: [Animal.Type]) -> [Animal] {
var arr = [Animal]()
for cls in clses {
arr.append(cls.init())
}
return arr
}
print(create([Cat.self, Dog.self, Pig.self]))
Copy the code
Animal() and animal.self.init () have the same effect. OC [[animal. class alloc] init]
The initialization method of the base Animal class is required. Why? Because the subclass initializer must implement the parent class initializer, it is possible to fail to find the init method and crash the program.
Example code 2: Swift supports some runtime functions.
class Person { var age: Int = 0 } class Student: Person { var no: Int = 0} print(class_getInstanceSize(student.self)) Person print(class_getSuperclass(person.self)!) // Output: _TtCs12_SwiftObjectCopy the code
As you can see from the results, Swift also has a hidden base class: swif.swiftobject
You can refer to Swift source code: github.com/apple/swift…
Fifth, the Self
Self
Represents the current type.
Sample code:
Class Person {var age = 1 static var count = 2 func run() {print(self.age); 2 } } var p = Person() p.run()Copy the code
Self
Typically used as a return value type (or as a parameter type), specifying that the return value must be of the same type as the method caller. Similar to OCinstancetype
.
Sample code:
protocol Runnable {
func test() -> Self
}
class Person: Runnable {
required init() { }
func test() -> Self {
type(of: self).init()
}
}
class Student: Person {
}
var p = Person()
p.test()
var stu = Student()
stu.test()
Copy the code
Result: the instance of the caller is returned.
For more articles in this series, please follow our wechat official account [1024 Planet].