通过代码片段比较 Swift 和 JavaScript

2018-07-14 11:52:30 +08:00
 unbug

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
}
1329 次点击
所在节点    前端开发
0 条回复

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

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

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

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

© 2021 V2EX