Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Swift - what's the difference between metatype .Type and .self?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

.Type The metatype of a class, structure, or enumeration type is the name of that type followed by .Type. The metatype of a protocol type—not the concrete type that conforms to the protocol at runtime

.Type

Under the hood AnyClass is

 

Basically where ever you see AnyClassAny.TypeAnyObject.Type,its because it‘s in need of a type. A very very common place we see it is when we want to register a class for our tableView using register func.

 

If you are confused as to what does ‘Swift.‘ do then above,then see the comments from here

The above Could have also been written as:

 

.self

Where is it used?

If you are writing/creating a function that accepts a type e.g. class, not an instance then to you would write T.Type as the type of the parameter. What it expects as a parameter can be: String.selfCustomTableView.selfsomeOtherClass.self.

In continuation of the tableView code:

 

Playground code:

 

Easy example

struct Something {

    var x = 5

}

 

let a = Something()

type(of:a) == Something.self // true

Hard example

class SomeBaseClass {

    class func printClassName() {

        print("SomeBaseClass")

    }

}

class SomeSubClass: SomeBaseClass {

    override class func printClassName() {

        print("SomeSubClass")

    }

}

 

 

let someInstance: SomeBaseClass = SomeSubClass()

/*                      |                |

                    compileTime       Runtime

                        |                | 

To extract,use:       .self          type(of)

 

  The compile-time type of someInstance is SomeBaseClass,

  and the runtime type of someInstance is SomeSubClass */

 

type(of: someInstance) == SomeSubClass.self // TRUE

type(of: someInstance) == SomeBaseClass.self // FALSE

 

I highly recommend to read Apple documentation on Types. Also see here

 

https://stackoverflow.com/questions/31438368/swift-whats-the-difference-between-Metatype-type-and-self

大佬总结

以上是大佬教程为你收集整理的Swift - what's the difference between metatype .Type and .self?全部内容,希望文章能够帮你解决Swift - what's the difference between metatype .Type and .self?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: