请问一个 Swift 的语法问题。

2017-07-21 09:30:59 +08:00
 isweal

在 OC 中可以这样写

NSTimeInterval timeInterval = [self timeIntervalSinceNow];
timeInterval = -timeInterval;
timeInterval = timeInterval - 8 * 60 * 60;
long temp = 0;
NSString *result;
if (timeInterval < 60) {
	result = [NSString stringWithFormat:@"just"];
} else if ((temp = (long) (timeInterval / 60)) < 60) {
	result = [NSString stringWithFormat:@"%ld m", temp];
} else if ((temp = temp / 60) < 24) {
	result = [NSString stringWithFormat:@"%ld h", temp];
}

就是在 if 的时候可以对 temp 同时进行赋值与比较,那么 swift3 可以这样写吗,试了一会总是报红。

3592 次点击
所在节点    Swift
10 条回复
JohnSmith
2017-07-21 09:53:17 +08:00
If let ?
isweal
2017-07-21 10:21:09 +08:00
@JohnSmith if let 后面只能接 optional type 啊。
yzyzsun
2017-07-21 10:34:30 +08:00
现在 Swift 的赋值语句没有返回值,不仅是这个例子,连续赋值( a = b = c )也是不行的
hekunhotmail
2017-07-21 11:10:34 +08:00
所以 swift 好傻逼啊,写点简洁的代码都不行,oc 想要写简洁点没啥障碍
isweal
2017-07-21 11:37:02 +08:00
@hekunhotmail swift 也有 swift 的好啊
hekunhotmail
2017-07-21 11:43:26 +08:00
@isweal 我只是说它这方面确实挺 low 得,好的地方都还不错
acumen
2017-07-21 13:15:55 +08:00
逗号表达式? if let temp = a, temp < 60
isweal
2017-07-21 14:10:16 +08:00
@acumen 不行的,你这里 a 必须是 optional
isweal
2017-07-21 14:11:13 +08:00
最后我用了一堆嵌套 if else 把之前写的 OC 代码翻译过去了。
acumen
2017-07-21 14:31:06 +08:00
@isweal 是的,如果非要这么写的话,a 用 optional 包一层。 看上去比较奇怪

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/376880

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX