Swift和Kotlin基礎語法比較

Swift和Kotlin基礎語法比較

內容翻譯自Github項目:Swift is like Kotlin

Hello World

Swift

<code>print("Hello, world!")/<code>

Kotlin

<code>println("Hello, world!")/<code>

變量和常量

Swift

<code>var myVariable = 42
myVariable = 50
let myConstant = 42/<code>

Kotlin

<code>var myVariable = 42
myVariable = 50
val myConstant = 42/<code>

顯式類型

Swift

<code>let explicitDouble: Double = 70/<code>

Kotlin

<code>val explicitDouble: Double = 70.0/<code>

類型轉換

Swift

Swift需顯式轉換

<code>let label = "The width is "
let width = 94
let widthLabel = label + String(width)/<code>

Kotlin

Kotlin可以隱式轉換

<code>val label = "The width is "
val width = 94
val widthLabel = label + width/<code>

字符串插值

Swift

Swift使用 “\\” 符號

<code>let apples = 3
let oranges = 5
let fruitSummary = "I have \\(apples + oranges) " +
"pieces of fruit."/<code>

Kotlin

Kotlin使用 “$” 符號

<code>val apples = 3
val oranges = 5
val fruitSummary = "I have ${apples + oranges} " +
"pieces of fruit."/<code>

區間運算

Swift

<code>et names = ["Anna", "Alex", "Brian", "Jack"]
et count = names.count
for i in 0..<count>print("Person \\(i + 1) is called \\(names[i])")
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
for index in 1...5 {
print("\\(index) times 5 is \\(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25/<count>/<code>

Kotlin

<code>val names = arrayOf("Anna", "Alex", "Brian", "Jack") 

val count = names.count()
for (i in 0..count - 1) {
println("Person ${i + 1} is called ${names[i]}")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
for (index in 1..5) {
println("$index times 5 is ${index * 5}")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25/<code>

數組

Swift

<code>var shoppingList = ["catfish", "water",
"tulips", "blue paint"]
shoppingList[1] = "bottle of water"/<code>

Kotlin

<code>val shoppingList = arrayOf("catfish", "water",
"tulips", "blue paint")
shoppingList[1] = "bottle of water"/<code>

字典

Swift使用 ":" 連接 key value

Swift

<code>var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"/<code>

Kotlin

Kotlin使用“to” 關鍵字 連接key value

<code>val occupations = mutableMapOf(
"Malcolm" to "Captain",

"Kaylee" to "Mechanic"
)
occupations["Jayne"] = "Public Relations"/<code>

空集

Swift

<code>let emptyArray = [String]()
let emptyDictionary = [String: Float]()/<code>

Kotlin

<code>val emptyArray = arrayOf<string>()
val emptyMap = mapOf<string>()/<string>/<string>/<code>

函數定義

Swift

<code>func greet(_ name: String,_ day: String) -> String {
return "Hello \\(name), today is \\(day)."
}
greet("Bob", "Tuesday")/<code>

Kotlin

<code>fun greet(name: String, day: String): String {
return "Hello $name, today is $day."
}
greet("Bob", "Tuesday")/<code>

可變數量參數

Swift

<code>func sumOf(_ numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf(42, 597, 12)/<code>

Kotlin

<code>fun sumOf(vararg numbers: Int): Int {
var sum = 0

for (number in numbers) {
sum += number
}
return sum
}
sumOf(42, 597, 12)
// 也可以使用另一種更簡短的定義方法
fun sumOf(vararg numbers: Int) = numbers.sum()/<code>

函數類型

Swift

<code>func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
let increment = makeIncrementer()
increment(7)/<code>

Kotlin

<code>fun makeIncrementer(): (Int) -> Int {
val addOne = fun(number: Int): Int {
return 1 + number
}
return addOne
}
val increment = makeIncrementer()
increment(7)
// 也可以使用另一種更簡短的寫法
fun makeIncrementer() = fun(number: Int) = 1 + number/<code>

Map映射

Swift

Swift使用 $

<code>let numbers = [20, 19, 7, 12]
numbers.map { 3 * $0 }/<code>

Kotlin

Kotlin使用 it

<code>val numbers = listOf(20, 19, 7, 12)
numbers.map { 3 * it }/<code>

Sort排序

Swift

<code>var mutableArray = [1, 5, 3, 12, 2]
mutableArray.sort()/<code>

Kotlin

<code>listOf(1, 5, 3, 12, 2).sorted()/<code>

具名參數

Swift

<code>func area(width: Int, height: Int) -> Int {
return width * height
}
area(width: 2, height: 3)/<code>

Kotlin

Kotlin混用位置參數與具名參數時,所有位置參數都要放在第一個具名參數之前。例如,允許調用 f(1, y = 2) 但不允許 f(x = 1, 2)。

<code>fun area(width: Int, height: Int) = width * height
area(width = 2, height = 3)

// This is also possible with named arguments
area(2, height = 2)
area(height = 3, width = 2)/<code>

類定義

Swift

<code>class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \\(numberOfSides) sides."
}
}/<code>

Kotlin

<code>class Shape {
var numberOfSides = 0
fun simpleDescription() =
"A shape with $numberOfSides sides."
}/<code>

對象實例化

Swift

<code>var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()/<code>

Kotlin

<code>var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()/<code>

子類繼承

Swift

<code>class NamedShape {
var numberOfSides: Int = 0
let name: String

init(name: String) {
self.name = name
}

func simpleDescription() -> String {
return "A shape with \\(numberOfSides) sides."
}
}

class Square: NamedShape {
var sideLength: Double

init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
self.numberOfSides = 4
}

func area() -> Double {

return sideLength * sideLength
}

override func simpleDescription() -> String {
return "A square with sides of length " +
sideLength + "."
}
}

let test = Square(sideLength: 5.2, name: "square")
test.area()
test.simpleDescription()/<code>

Kotlin

Kotlin類繼承,需在父類用open關鍵字顯式聲明

<code>open class NamedShape(val name: String) {
var numberOfSides = 0

open fun simpleDescription() =
"A shape with $numberOfSides sides."
}

class Square(var sideLength: BigDecimal, name: String) :
NamedShape(name) {
init {
numberOfSides = 4
}

fun area() = sideLength.pow(2)

override fun simpleDescription() =
"A square with sides of length $sideLength."
}

val test = Square(BigDecimal("5.2"), "square")
test.area()
test.simpleDescription()/<code>

對象類型檢查

Swift

<code>var movieCount = 0
var songCount = 0

for item in library {

if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}/<code>

Kotlin

<code>var movieCount = 0
var songCount = 0

for (item in library) {
if (item is Movie) {
++movieCount
} else if (item is Song) {
++songCount
}
}/<code>

變量匹配

Swift

Swift使用switch函數,同時去掉了break

<code>let nb = 42
switch nb {
case 0...7, 8, 9: print("single digit")
case 10: print("double digits")
case 11...99: print("double digits")
case 100...999: print("triple digits")
default: print("four or more digits")
}/<code>

Kotlin

Kotlin引入了新的when語句,來處理變量匹配,同時在when內使用“->”箭頭函數

<code>val nb = 42
when (nb) {
in 0..7, 8, 9 -> println("single digit")
10 -> println("double digits")
in 11..99 -> println("double digits")
in 100..999 -> println("triple digits")
else -> println("four or more digits")

}/<code>

遍歷對象

Swift

Swift for語句去掉了()

<code>for current in someObjects {
if let movie = current as? Movie {
print("Movie: '\\(movie.name)', " +
"dir. \\(movie.director)")
}
}/<code>

Kotlin

Kotlin for語句保留了()

<code>for (current in someObjects) {
if (current is Movie) {
println("Movie: '${current.name}', " +
"dir. ${current.director}")
}
}/<code>

接口

Swift

Swift使用 protocol 關鍵字

<code>protocol Nameable {
func name() -> String
}

func f(x: T) {
print("Name is " + x.name())
}
/<code>

Kotlin

Kotlin使用 interface 關鍵字

<code>interface Nameable { 

fun name(): String
}

fun f(x: T) {
println("Name is " + x.name())
}
/<code>

擴展

Swift

Swift需使用extension關鍵字

<code>extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("One inch is \\(oneInch) meters")
// 輸出 "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \\(threeFeet) meters")
// 輸出 "Three feet is 0.914399970739201 meters"/<code>

Kotlin

Kotlin則直接使用“.”符號

<code>val Double.km: Double get() = this * 1000
val Double.m: Double get() = this
val Double.cm: Double get() = this / 100
val Double.mm: Double get() = this / 1000
val Double.ft: Double get() = this / 3.28084

val oneInch = 25.4.mm
println("One inch is $oneInch meters")
// 輸出 "One inch is 0.0254 meters"
val threeFeet = 3.0.ft
println("Three feet is $threeFeet meters")
// 輸出 "Three feet is 0.914399970739201 meters"/<code>

親愛的朋友;相對Swift和Kotlin的語法,你們更喜歡哪一種呢?當然Swift和Kotlin都是非常現代化的編程語言,在很多方面都已經趨同類似,兩個都是非常優秀的語言。


Swift和Kotlin基礎語法比較


分享到:


相關文章: