【问题标题】:How do I get the instantiated type of a class in Swift?如何在 Swift 中获取类的实例化类型?
【发布时间】:2021-10-14 11:39:01
【问题描述】:

我是一名 C# 程序员,试图了解 Swift 的类型系统。下面的代码定义了一个带有访问器getTypeOfFruit() 的超类fruit。我希望它返回实例化类型而不是超类的类型。

旁白:有没有关于 Swift 类型系统的高级文档?我遇到的大部分内容都只涉及基础知识。

public class Fruit {
    private var fruitType = Fruit.Type.self      // generic fruit type
    public func getTypeOfFruit<T>() -> T.Type  { 
        return fruitType as! T.Type              //
    }
}

public class Apple: Fruit { 

}

public class TimApple: Apple {
}

var fruit = Fruit.self        // error:  Instance member 'getTypeOfFruit' cannot be used
print(fruit.getTypeOfFruit()) // should print "Fruit"

var fruit = Apple.self
print(fruit.getTypeOfFruit()) // should print "Apple"

fruit = TimApple.self
print(fruit.getTypeOfFruit()) // should print "TimApple"

【问题讨论】:

    标签: swift types


    【解决方案1】:

    您可以使用type(of:),例如,

    public class Fruit {
        public func getTypeOfFruit() -> Fruit.Type  {
            return type(of: self)
        }
    }
    
    public class Apple: Fruit { }
    
    public class TimApple: Apple { }
    
    var fruit = Fruit()
    print(fruit.getTypeOfFruit()) // prints "Fruit"
    
    fruit = Apple()
    print(fruit.getTypeOfFruit()) // prints "Apple"
    
    fruit = TimApple()
    print(fruit.getTypeOfFruit()) // print "TimApple"
    

    【讨论】:

    • 我正在挖掘这种快速语言的东西。苹果总是做对了。我想知道当调用 type() 很容易时使用访问器是否有意义。你知道一些涵盖 Swift 类型系统的更深层次的文献吗?它似乎有一个类似 F# 的类型代数。太糟糕了 C# 没有接受其中的一些。
    • 有方法有意义吗,getTypeOfFruit?正如您所指出的,type(of:) 很简单。或者,更好的是,对于大多数用例来说,与其完全依赖 reflection 相比,原生类型检查/转换更自然(例如,if fruit is TimApple { … }switch fruit { case let tim as TimApple: … } 等)。反射更多是一种调试模式,在生产代码中,通常有更好的方法。
    • 关于类型系统的重新文档,除了 Apple 的 Resources page,没有什么特别值得一提的了。
    • OK 我仍然可以将类型存储在 var 中并在不使用反射的情况下进行比较吗? IE。我如何设置水果只包含类型。
    • 我会小心存储类型并稍后进行比较。例如。如果您有另一个子类,class GreenApple: Apple { }。现在你保存它的type(of:)if greenApple is Apple { … } 的测试有效,但像 if greenAppleType == Apple.self { … } 这样的测试无效。青苹果是苹果,是水果。通常,您希望类型检查以尊重继承(例如“is kind of”,包括子类)而不是寻找特定实例(例如“is member of”,不包括子类)。例如。 if greenAppleType is Apple.Type { … }.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多