我想将这两个Obj-C语句转换为Swift。我不确定语法,因为有多个对象百分号。除了带有百分号的打印字符串之外,我已经转换了大部分代码。
我想使用Swift的原生打印(" \ variable")语法。
self.validFrames.text = [NSString stringWithFormat:@" Valid Frames:%d %%",MIN(100,(100 * self.validFrameCounter)/ MIN_FRAMES_FOR_FILTER_TO_SETTLE)];
validFrames.text = String.localizedStringWithFormat("Valid Frames: \min%%"(100, (100 * validFrameCounter) / minFramesForFilterToSettle))
self.rate.text = [NSString stringWithFormat:@"%0.0f",beat];
rate.text = String.localizedStringWithFormat("\beat 0.0f")
请更正我的Swift语法。
答案 0 :(得分:1)
插值语法为\(expression)
:
let validFramesPercentage = MIN(100, (100 * self.validFrameCounter)/MIN_FRAMES_FOR_FILTER_TO_SETTLE)
self.validFrames.text = "Valid Frames: \(validFramesPercentage)%"
如果使用插值语法,则无法控制Swift如何格式化浮点数。例如:
let beat = Float(10.0/3)
self.rate.text = "\(beat)"
// text is 3.33333; you can't specify the number of digits
如果要使用本地化字符串,则无法使用\(...)
插值。要执行插值,编译器必须检查字符串。本地化字符串在运行时从数据文件加载。编译器不会查看它们。
在Swift中使用格式字符串是100%正常。它们是图书馆的一部分,就像UIView
(或NSView
)一样。
答案 1 :(得分:0)
我担心你无法使用插值sintax 来达到你想要的效果。
您应该使用Float
:
var text = String.localizedStringWithFormat("%0.0f", 2.0) // result: 2
对于Int
:
var text = String.localizedStringWithFormat("%d%%", 10) // result 10%