Kotlin和Swift横向对比

kotlin面世已经有不短的时间了,从安卓宣布kotin为安卓官方开发语言开始,kotlin的热度开始猛涨,作为一个从swift1.0开始写iOS程序的开发者自然会对这两门语言做一些对比,本篇文章主要介绍两个语言的基础语法的对比。

  • 变量

Kotlin Swift
var a: Int = 1 var a: Int = 1
var b = 2 var b = 2
val a: Int = 1 let a: Int = 1
val b = 2 let b = 2
var str: String? = null var str: String? = nil
var x = 5
x += 1
var x = 1
x += 1
val a = 1
val s1 = "a is $a"
val s2 = "${s1.replace("is", "was")}, but now is $a"
let a = 1
let s1 = "a is \(a)"
let s2 = "\(s1.replacingCharacters(in: "is", with: "was")), but now is \(a)"
  • 方法

Kotlin

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

Swift

func maxOf(a: Int, b: Int) -> Int {
    if  a > b {
        return a
    } else {
        return b
    }
}
  • for循环

Kotlin

val items = listOf("apple", "banana", "kiwi")
for (item in items) {
    println(item)
}

Swift

let items = ["apple", "banana", "kiwi"]
for item in items {
      print(item)
}
  • while循环

Kotlin

val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}

Swift

let items = ["apple", "banana", "kiwi"]
        
repeat {
    print("item at $index is ${items[index]}")
    index++
} while index < items.count
  • switch循环

Kotlin

fun describe(obj: Any): String =
when (obj) {
   1          -> "One"
   "Hello"    -> "Greeting"
   is Long    -> "Long"
   !is String -> "Not a string"
   else       -> "Unknown"
}

Swift

func describe(obj: Any) -> String {
    switch obj {
    case 1:                  return "One"
    case "Hello":            return "Greeting"
    case is Int:             return "Int"
    case !(is String):       return "Not a string"
    default:                 return "Unknown"
    }
}
  • Class

Kotlin

class Invoice {
}

class Person(firstName: String) {
}

Swift

class Invoice {
}

class Person {
    var firstName: String!
    
    init(firstName: String) {
        self.firstName = firstName
    }
}
  • enum

Kotlin

enum class Direction {
    NORTH, SOUTH, WEST, EAST
}

Swift

enum Direction {
    NORTH, SOUTH, WEST, EAST
}

总结

从上面的一些对比可以看到,kotlin的语法和swift的语法大致相同,但也存在一些差异,总的来说这两个语言的设计思想都是差不多的。 还有一些更加深的语法本文并没有涉及,感兴趣的同学可以到kotlin官网和Swift官网了解更多。

目前这两者都支持服务端开发,也都是开源的编程语言,就看以后怎么一决高下了,我认为kotlin成也因为jvm,败也因为jvm,未来怎样就看开发者怎么去支持了。

你可能感兴趣的:(Kotlin和Swift横向对比)