V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
isweal
V2EX  ›  Swift

请问一个 Swift 的语法问题。

  •  
  •   isweal · 2017-07-21 09:30:59 +08:00 · 3554 次点击
    这是一个创建于 2442 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在 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 可以这样写吗,试了一会总是报红。

    10 条回复    2017-07-21 14:31:06 +08:00
    JohnSmith
        1
    JohnSmith  
       2017-07-21 09:53:17 +08:00 via Android
    If let ?
    isweal
        2
    isweal  
    OP
       2017-07-21 10:21:09 +08:00
    @JohnSmith if let 后面只能接 optional type 啊。
    yzyzsun
        3
    yzyzsun  
       2017-07-21 10:34:30 +08:00 via iPad
    现在 Swift 的赋值语句没有返回值,不仅是这个例子,连续赋值( a = b = c )也是不行的
    hekunhotmail
        4
    hekunhotmail  
       2017-07-21 11:10:34 +08:00
    所以 swift 好傻逼啊,写点简洁的代码都不行,oc 想要写简洁点没啥障碍
    isweal
        5
    isweal  
    OP
       2017-07-21 11:37:02 +08:00 via iPhone
    @hekunhotmail swift 也有 swift 的好啊
    hekunhotmail
        6
    hekunhotmail  
       2017-07-21 11:43:26 +08:00
    @isweal 我只是说它这方面确实挺 low 得,好的地方都还不错
    acumen
        7
    acumen  
       2017-07-21 13:15:55 +08:00
    逗号表达式? if let temp = a, temp < 60
    isweal
        8
    isweal  
    OP
       2017-07-21 14:10:16 +08:00
    @acumen 不行的,你这里 a 必须是 optional
    isweal
        9
    isweal  
    OP
       2017-07-21 14:11:13 +08:00
    最后我用了一堆嵌套 if else 把之前写的 OC 代码翻译过去了。
    acumen
        10
    acumen  
       2017-07-21 14:31:06 +08:00
    @isweal 是的,如果非要这么写的话,a 用 optional 包一层。 看上去比较奇怪
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2418 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:10 · PVG 00:10 · LAX 09:10 · JFK 12:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.