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

通过代码片段比较 Swift 和 JavaScript

  •  
  •   unbug · 2018-07-14 11:52:30 +08:00 · 1403 次点击
    这是一个创建于 2354 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Swift and JavaScript comparison snippets

    Issue and pull request are welcome, please!

    Table of content

    The Basics

    Constants and Variables

    Swift

    // declare a constant 
    let maximumNumberOfLoginAttempts = 10
    
    // declare a variable
    var currentLoginAttempt = 0
    
    // declare multiple constants or multiple variables on a single line, separated by commas
    var x = 0.0, y = 0.0, z = 0.0
    

    JavaScript

    // declare a constant 
    const maximumNumberOfLoginAttempts = 10
    
    // declare a variable
    var currentLoginAttempt = 0 
    // or 
    let currentLoginAttempt = 0
    
    // declare multiple constants or multiple variables on a single line, separated by commas
    var x = 0.0, y = 0.0, z = 0.0
    
    

    Comments

    Swift

    // This is a comment.
    
    /* This is also a comment
    but is written over multiple lines. */
    
    

    JavaScript

    // This is a comment.
    
    /* This is also a comment
    but is written over multiple lines. */
    
    

    Numeric Type Conversion

    Swift

    let pi = 3.14159
    // Integer and Floating-Point Conversion
    let integerPi = Int(pi)
    

    JavaScript

    const pi = 3.14159
    // Integer and Floating-Point Conversion
    const integerPi = parseInt(pi)
    

    Booleans

    Swift

    let orangesAreOrange = true
    let turnipsAreDelicious = false
    
    if turnipsAreDelicious {
        print("Mmm, tasty turnips!")
    } else {
        print("Eww, turnips are horrible.")
    }
    

    JavaScript

    const orangesAreOrange = true
    const turnipsAreDelicious = false
    
    if (turnipsAreDelicious) {
        console.log("Mmm, tasty turnips!")
    } else {
        console.log("Eww, turnips are horrible.")
    }
    

    Error Handling

    Swift

    func canThrowAnError() throws {
        // this function may or may not throw an error
    }
    do {
        try canThrowAnError()
        // no error was thrown
    } catch {
        // an error was thrown
    }
    
    

    JavaScript

    function canThrowAnError() {
        // this function may or may not throw an error
    }
    try {
        canThrowAnError()
        // no error was thrown
    } catch (e) {
        // an error was thrown
    }
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5420 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 07:37 · PVG 15:37 · LAX 23:37 · JFK 02:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.