在初始化swift期间设置类属性

时间:2016-05-23 17:00:59

标签: ios swift nsnumberformatter

我正在尝试创建两个NSNumberFormater对象 - 一个的maximumFractionDigits为0,另一个的maximumFractiongDigits为6.我想在初始化期间这样做,所以我可以重复使用这些对象。我现在拥有的是:

private let formatter = NSNumberFormatter()

private var niceAccumulator : String {
    if accumulator % 1 == 0 {
        formatter.maximumFractionDigits = 0
        return String(formatter.stringFromNumber(accumulator)!)
    }
    else {
        formatter.maximumFractionDigits = 6
        return String(formatter.stringFromNumber(accumulator)!)
    }
}

我想做的是:

private let intFormatter = NSNumberFormatter(maximumFractionDigits: 0)
private let doubleFormatter = NSNumberFormatter(maximumFractionDigits: 6)

private var niceAccumulator : String {
    if accumulator % 1 == 0 {
        return String(intFormatter.stringFromNumber(accumulator)!)
    }
    else {
        return String(doubleFormatter.stringFromNumber(accumulator)!)
    }
}

我正在学习再次编码,所以我真的很感激帮助。谢谢大家!

3 个答案:

答案 0 :(得分:1)

您有两种选择。正如@TofuBeer在他的回答中指出的那样,你可以使用初始化器:

private let intFormatter: NSNumberFormatter
private let doubleFormatter: NSNumberFormatter

init() {
    intFormatter = NSNumberFormatter()
    intFormatter.maximumFractionDigits = 0
    doubleFormatter = NSNumberFormatter()
    doubleFormatter.maximumFractionDigits = 6

    // Call to an appropriate super.init, assuming you are subclassing something
}

如果您不想使用初始化程序,也可以使用闭包来初始化您的属性:

private let intFormatter: NSNumberFormatter = {
    let formatter = NSNumberFormatter()
    formatter.maximumFractionDigits = 0
    return formatter
}()

private let doubleFormatter: NSNumberFormatter = {
    let formatter = NSNumberFormatter()
    formatter.maximumFractionDigits = 6
    return formatter
}()

答案 1 :(得分:1)

如果您发现需要在项目中使用此构造,则值得指出您可以定义自己的便利初始化程序:

data = OrderedDict(
    ('class' if k == 'tool_class' else k, v) for (k, v) in data.items()
)

然后你可以这样做:

extension NSNumberFormatter {
    convenience init(maximumFractionDigits: Int) {
        self.init()
        self.maximumFractionDigits = maximumFractionDigits
    }
}

答案 2 :(得分:0)

使用initializer

private let intFormatter = NSNumberFormatter()
private let doubleFormatter = NSNumberFormatter()

init() 
{
    intFormatter.maximumFractionDigits = 0
    doubleFormatter.maximumFractionDigits = 6
}