需要知道在外类中定义的Inner类的变量名

时间:2017-03-02 20:55:18

标签: swift

我有这两个类:

class User:Obj
{
    var firstBook:Book?
    var secondBook:Book?
}

class Book:Obj
{
   func getMyName() -> String
   {
      // Something need to do here
      // return name
   }
}

let user = User()

let book_1 = Book()
user.firstBook = book_1

let book_2 = Book()
user.secondBook = book_2

print(book_2.getMyName()) //Expected: secondBook
print(book_1.getMyName()) //Expected: firstBook

如您所知,我需要获取父类的变量名称。 如果能够获得父类,那将会很棒。类型

2 个答案:

答案 0 :(得分:2)

你可以使用反射来实现类似的东西。您需要了解book对象中的用户对象,因此我添加了一个父变量。它需要很弱,以避免保留周期。

class User: Obj {

    var firstBook: Book? {
        didSet {
            firstBook?.parent = self
        }
    }

    var secondBook: Book?  {
        didSet {
            secondBook?.parent = self
        }
    }

}

class Book: Obj {

    weak var parent: Obj!

    func getMyName() -> String {
        let mirror = Mirror(reflecting: parent)
        let variableName = mirror.children.filter { $0.value as? Book === self }.first?.label
        return variableName!
    }

}

答案 1 :(得分:1)

您可以在Book类中创建属性作为名称,并将name属性设置为firstBook和secondBook,并通过检索名称属性来获取它