如何在运行时确定通用变量的值?

时间:2018-08-26 20:08:29

标签: swift xcode generics

以下代码段显示了通用变量“ A”。

我试图找出此load()返回的nil的来源。

这是代码段:

final class Cache {
    var storage = FileStorage()

    // 1) 'load': Read from the Cache:
    func load<A>(_ resource: Resource<A>) -> A? {
        print("--- LOAD ---")
        guard case .get = resource.method else { return nil }
        // Type of 'data' is optional.
        let diskData = storage[resource.cacheKey] // ...type: Data? (optional-Data).
        // Want to convert diskData to A? (optional-A):
        return diskData.flatMap(resource.parse) // ...cleaning data, removing nils.
    }

    // 2) 'save' to the Cache:
    func save<A>(_ data: Data, for resource: Resource<A>) {
        print("--- SAVE ---")
        guard case .get = resource.method else { return }
        self.storage[resource.cacheKey] = data
    }
}

// ----------------------------------

// MARK: -  Resource

public struct Resource<A> {
    public var url: URL
    public var parse: (Data) -> A? // ... convert Data to A?
    public var method: HttpMethod<Data> = .get

    public init(url: URL, parse: @escaping (Data) -> A?, method: HttpMethod<Data> = .get) {
        self.url = url
        self.parse = parse
        self.method = method
    }
}

// ----------------------------------

同时,如何在运行时调试期间确定任何通用变量的值?

也就是说,谁确定A的值?

注意:代码是通过objc.io上的“ Swift Talk”来自共享源的。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

要找出A代表什么类型,请打印具有包含通用类型占位符的类型的变量的类型。

对于您来说,resource的类型为Resource<A>,因此:

p type(of: resource)

将显示如下内容:

<ProjectName>.Resource<Int>

在这种情况下,AInt

相关问题