Get the name (string) of a generic type in Swift

后端 未结 6 1239
别那么骄傲
别那么骄傲 2020-12-17 08:10

I have a generic class of type T and I would like to get the name of the type that passed into the class when instantiated. Here is an example.

class MyClas         


        
6条回答
  •  我在风中等你
    2020-12-17 08:56

    A pure swift way to achieve that is not possible.

    A possible workaround is:

    class MyClass {
        func genericName() -> String {
            let fullName: String = NSStringFromClass(T.self)
            let range = fullName.rangeOfString(".", options: .BackwardsSearch)
            if let range = range {
                return fullName.substringFromIndex(range.endIndex)
            } else {
                return fullName
            }
        }
    }
    

    The limitations relies on the fact that it works with classes only.

    If this is the generic type:

    class TestClass {}
    

    NSStringFromClass() returns the full name (including namespace):

    // Prints something like "__lldb_expr_186.TestClass" in playground
    NSStringFromClass(TestClass.self)
    

    That's why the func searches for the last occurrence of the . character.

    Tested as follows:

    var x = MyClass()
    x.genericName() // Prints "TestClass"
    

    UPDATE Swift 3.0

    func genericName() -> String {
        let fullName: String = NSStringFromClass(T.self)
        let range = fullName.range(of: ".")
        if let range = range {
            return fullName.substring(from: range.upperBound)
        }
        return fullName
    }
    

提交回复
热议问题