重新初始化静态变量

SSB*_*B95 4 swift

我的设置VC中有一个简单的tableview。有两种不同的情况,即登录的用户是雇员还是管理员。管理员能够将用户添加到组织中,因此他看到两个部分,每个部分一行(添加用户并注销),而普通员工只看到一个一行(注销)。要管理indexPaths,我具有以下结构:

struct Indexes {
    struct AddEmployee {
        static let row = 0
        static let section = isEmployee() ? -1 : 0
        static func indexPath() -> IndexPath {
            return IndexPath(row: row, section: section)
        }
    }

    struct SignOut {
        static let row = 0
        static let section = isEmployee() ? 0 : 1
        static func indexPath() -> IndexPath {
            return IndexPath(row: row, section: section)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的TableView委托中,我得到了以下方法:

func numberOfSections(in tableView: UITableView) -> Int {
    return isEmployee() ? 1 : 2
}
Run Code Online (Sandbox Code Playgroud)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsTableViewCell", for: indexPath)
        if (indexPath == Indexes.AddEmployee.indexPath()) {
            cell.textLabel?.text = "Add Employee"
        } else if (indexPath == Indexes.SignOut.indexPath()) {
            cell.textLabel?.text = "Log out"
        }
        return cell
    }
Run Code Online (Sandbox Code Playgroud)

现在的问题是,当我以Admin身份登录并以Employee身份登录时(反之亦然),static结构的变量仍会初始化,并且isEmployee()返回值已更改这一事实无关紧要,因为变量不是重新加载,所以我的单元格数量错误。是否有可能迫使结构重新加载其静态变量?

Mat*_*man 5

没有一种方法可以强制结构重新加载其静态存储的常量,但是您只需要使用静态的计算变量即可。

计算出的变量如下所示:

static var section: Int {
    get {
        return isEmployee() ? -1 : 0
    }
}
Run Code Online (Sandbox Code Playgroud)

计算变量实际上并没有存储,而是在您每次调用它们时进行计算。除非您的逻辑需要很长时间才能执行,否则不会有问题。即使已将其标记为varnot let,但它仍将是只读的,因为您仅指定了一个getter(您可能已经在该set块下面指定了一个setter并带有一个get块)。

作为一种快捷方式,get当您只想要吸气剂时,无需显式显示关键字和花括号,因此您可以摆脱它们。您还有:

struct Indexes {
    struct AddEmployee {
        static let row = 0
        static var section: Int {
            return isEmployee() ? -1 : 0
        }
        static func indexPath() -> IndexPath {
            return IndexPath(row: row, section: section)
        }
    }

    struct SignOut {
        static let row = 0
        static var section: Int {
            return isEmployee() ? 0 : 1
        }
        static func indexPath() -> IndexPath {
            return IndexPath(row: row, section: section)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您愿意,甚至可以转换indexPath为计算变量而不是函数,它会做同样的事情。在Swift中,一个常见的约定是在不需要参数且使用逻辑来获取结​​果的时候很琐碎,因此不会花费很长时间。