天天看點

swift的類型系統及類型(記憶體)資訊擷取:接口、編譯運作時、反射、記憶體布局...

swift是靜态語言,沒有在運作時儲存類型的結構資訊(isa、class)。

一、self、Self、Type、typeof

extension Collection where Self.Element == UInt8, Self.Index == Int

public static func isValueTypeOrSubtype(_ value: Any) -> Bool {

        return value is Self

    }

static func _transform(dict: [String: Any]) -> _ExtendCustomModelType? {

        var instance: Self

        if let _nsType = Self.self as? NSObject.Type {

            instance = _nsType.createInstance() as! Self

        } else {

            instance = Self.init()

        }

        _transform(dict: dict, to: &instance)

        instance.didFinishMapping()

        return instance

    }

let someInstance: SomeBaseClass = SomeSubClass()

/*                      |                |

                    compileTime       Runtime

                        |                | 

To extract, use:       .self          type(of)

  • metatype-type –>type.Type|type.Protocol
  • type-as-value –>type.self

1. In a protocol, it refers to the type that conforms to the protocol in any particular use. In Equatable, for example, it's used to require that the two values being compared are of the same type. It's something like a generic type parameter that you don't have to put between the <…> because it's deduced from the context of its use.

2. In a class/static method, it can be used as the return type, to indicate that the return type is the type of the class to which the method was sent, rather than the class in which the method is declared. It's similar to 'instancetype' in Obj-C.

Self相當于oc中的instance

是什麼

相信大家都知道self這個關鍵字的具體作用,它跟OC裡的self基本一樣。但是對于Self來說...(WTF,這是什麼東西)

當你用錯Self的時候編譯器會這樣提示

'Self' is only available in a protocol or as the result of a method in a class

分割開來的話就是兩個意思

1.Self可以用于協定(protocol)中限制相關的類型

2.Self可以用于類(Class)中來充當方法的傳回值類型

二、記憶體布局

unsafeMutableRawPointer

 三、反射

let mirror = Mirror(reflecting: self)

for child in mirror.children {

    print("Property name:", child.label)

    print("Property value:", child.value)

}

https://www.swiftbysundell.com/posts/reflection-in-swift

四、記憶體資訊擷取

Looking up the elements in structs, classes, and enums is currently quite complex. Much of this complexity is due to the lack of a direct reference between these types and the field descriptors which contain the information about a type’s fields. A helper function called 

swift_getFieldAt

 searches for the appropriate field descriptor for a given type. This whole function should go away once we add that direct reference, but in the meantime it provides an interesting look at how the runtime code is able to use the language’s metadata to look up type information.

https://mjtsai.com/blog/2018/09/28/how-swifts-mirror-works/

轉載于:https://www.cnblogs.com/feng9exe/p/10406668.html

繼續閱讀