當前位置:
首頁 > 知識 > Kotlin 就像Swift?看看 Kotlin與Swift 的簡單對比

Kotlin 就像Swift?看看 Kotlin與Swift 的簡單對比

原文:http://nilhcem.com/swift-is-like-kotlin/

一位國外的程序員認為 Swift 的語法與 Kotlin 相似,並整理了一些 Swift 和 Kotlin 的對比,下面是一些例子,大家不妨也看看。

BASICS

Hello World

Swift

print("Hello, world!")

Kotlin

println("Hello, world!")

變數和常量

Swift

varmyVariable=42

myVariable=50

letmyConstant=42

Kotlin

varmyVariable=42

myVariable=50

valmyConstant=42

顯式類型

Swift

let explicitDouble: Double = 70

Kotlin

val explicitDouble: Double = 70.0

強制類型轉換

Swift

letlabel="The width is "

letwidth=94

letwidthLabel=label+String(width)

Kotlin

vallabel="The width is "

valwidth=94

valwidthLabel=label+width

字元串插值

Swift

letapples=3

letoranges=5

letfruitSummary="I have (apples + oranges) "+

"pieces of fruit."

Kotlin

valapples=3

valoranges=5

valfruitSummary="I have $ "+

"pieces of fruit."

範圍操作符

Swift

letnames=["Anna","Alex","Brian","Jack"]

letcount=names.count

foriin0..

Kotlin

valnames=arrayOf("Anna","Alex","Brian","Jack")

valcount=names.count()

for(iin0..count-1){

println("Person $ is called $")

}

// Person 1 is called Anna

// Person 2 is called Alex

// Person 3 is called Brian

// Person 4 is called Jack

包羅廣泛的範圍操作符(Inclusive Range Operator)

Swift

forindexin1...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

Kotlin

for(indexin1..5){

println("$index times 5 is $")

}

// 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

BASICS

數組

Swift

varshoppingList=["catfish","water",

"tulips","blue paint"]

shoppingList[1]="bottle of water"

Kotlin

valshoppingList=arrayOf("catfish","water",

"tulips","blue paint")

shoppingList[1]="bottle of water"

映射

Swift

varoccupations=[

"Malcolm":"Captain",

"Kaylee":"Mechanic",

]

occupations["Jayne"]="Public Relations"

Kotlin

valoccupations=mutableMapOf(

"Malcolm"to"Captain",

"Kaylee"to"Mechanic"

)

occupations["Jayne"]="Public Relations"

空集合

Swift

letemptyArray=[String]()

letemptyDictionary=[String:Float]()

Kotlin

valemptyArray=arrayOf()

valemptyMap=mapOf()

FUNCTIONS

函數

Swift

funcgreet(_name:String,_day:String)->String{

return"Hello (name), today is (day)."

}

greet("Bob","Tuesday")

Kotlin

fungreet(name:String,day:String):String{

return"Hello $name, today is $day."

}

greet("Bob","Tuesday")

元組返回

Swift

funcgetGasPrices()->(Double,Double,Double){

return(3.59,3.69,3.79)

}

Kotlin

dataclassGasPrices(vala:Double,valb:Double,

valc:Double)

fungetGasPrices()=GasPrices(3.59,3.69,3.79)

參數的變數數目(Variable Number Of Arguments)

Swift

funcsumOf(_numbers:Int...)->Int{

varsum=

fornumberinnumbers{

sum+=number

}

returnsum

}

sumOf(42,597,12)

Kotlin

funsumOf(varargnumbers:Int):Int{

varsum=

for(numberinnumbers){

sum+=number

}

returnsum

}

sumOf(42,597,12)

// sumOf() can also be written in a shorter way:

funsumOf(varargnumbers:Int)=numbers.sum()

函數類型

Swift

funcmakeIncrementer()->(Int->Int){

funcaddOne(number:Int)->Int{

return1+number

}

returnaddOne

}

letincrement=makeIncrementer()

increment(7)

Kotlin

funmakeIncrementer():(Int)->Int{

valaddOne=fun(number:Int):Int{

return1+number

}

returnaddOne

}

valincrement=makeIncrementer()

increment(7)

// makeIncrementer can also be written in a shorter way:

funmakeIncrementer()=fun(number:Int)=1+number

映射

Swift

letnumbers=[20,19,7,12]

numbers.map{3*$}

Kotlin

valnumbers=listOf(20,19,7,12)

numbers.map{3*it}

排序

Swift

varmutableArray=[1,5,3,12,2]

mutableArray.sort()

Kotlin

listOf(1, 5, 3, 12, 2).sorted()

命名參數

Swift

funcarea(width:Int,height:Int)->Int{

returnwidth*height

}

area(width:2,height:3)

Kotlin

funarea(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)

CLASSES

聲明

Swift

classShape{

varnumberOfSides=

funcsimpleDescription()->String{

return"A shape with (numberOfSides) sides."

}

}

Kotlin

classShape{

varnumberOfSides=

funsimpleDescription()=

"A shape with $numberOfSides sides."

}

用法

Swift

varshape=Shape()

shape.numberOfSides=7

varshapeDescription=shape.simpleDescription()

Kotlin

varshape=Shape()

shape.numberOfSides=7

varshapeDescription=shape.simpleDescription()

子類

Swift

classNamedShape{

varnumberOfSides:Int=

letname:String

init(name:String){

self.name=name

}

funcsimpleDescription()->String{

return"A shape with (numberOfSides) sides."

}

}

classSquare:NamedShape{

varsideLength:Double

init(sideLength:Double,name:String){

self.sideLength=sideLength

super.init(name:name)

self.numberOfSides=4

}

funcarea()->Double{

returnsideLength*sideLength

}

overridefuncsimpleDescription()->String{

return"A square with sides of length "+

sideLength+"."

}

}

lettest=Square(sideLength:5.2,name:"square")

test.area()

test.simpleDescription()

Kotlin

openclassNamedShape(valname:String){

varnumberOfSides=

openfunsimpleDescription()=

"A shape with $numberOfSides sides."

}

classSquare(varsideLength:BigDecimal,name:String):

NamedShape(name){

init{

numberOfSides=4

}

funarea()=sideLength.pow(2)

overridefunsimpleDescription()=

"A square with sides of length $sideLength."

}

valtest=Square(BigDecimal("5.2"),"square")

test.area()

test.simpleDescription()

類型檢查

Swift

varmovieCount=

varsongCount=

foriteminlibrary{

ifitemisMovie{

movieCount+=1

}elseifitemisSong{

songCount+=1

}

}

Kotlin

varmovieCount=

varsongCount=

for(iteminlibrary){

if(itemisMovie){

++movieCount

}elseif(itemisSong){

++songCount

}

}

模式匹配

Swift

letnb=42

switchnb{

case0...7,8,9:print("single digit")

case10:print("double digits")

case11...99:print("double digits")

case100...999:print("triple digits")

default:print("four or more digits")

}

Kotlin

valnb=42

when(nb){

in0..7,8,9->println("single digit")

10->println("double digits")

in11..99->println("double digits")

in100..999->println("triple digits")

else->println("four or more digits")

}

類型向下轉換

Swift

forcurrentinsomeObjects{

ifletmovie=currentas?Movie{

print("Movie: (movie.name) , "+

"dir. (movie.director)")

}

}

Kotlin

for(currentinsomeObjects){

if(currentisMovie){

println("Movie: $ , "+

"dir. $")

}

}

協議

Swift

protocolNameable{

funcname()->String

}

funcf(x:T){

print("Name is "+x.name())

}

Kotlin

interfaceNameable{

funname():String

}

funf(x:T){

println("Name is "+x.name())

}

擴展

Swift

extensionDouble{

varkm:Double{returnself*1_000.0}

varm:Double{returnself}

varcm:Double{returnself/100.0}

varmm:Double{returnself/1_000.0}

varft:Double{returnself/3.28084}

}

letoneInch=25.4.mm

print("One inch is (oneInch) meters")

// prints "One inch is 0.0254 meters"

letthreeFeet=3.ft

print("Three feet is (threeFeet) meters")

Kotlin

valDouble.km:Doubleget()=this*1000

valDouble.m:Doubleget()=this

valDouble.cm:Doubleget()=this/100

valDouble.mm:Doubleget()=this/1000

valDouble.ft:Doubleget()=this/3.28084

valoneInch=25.4.mm

println("One inch is $oneInch meters")

// prints "One inch is 0.0254 meters"

valthreeFeet=3.0.ft

println("Three feet is $threeFeet meters")

點擊展開全文

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序猿 的精彩文章:

兩年波折路(考研、工作、考研)
震驚!正經遊戲公司為何員工連續跳樓,真相竟然是……
編程到底難在哪裡?

TAG:程序猿 |

您可能感興趣

Spring Boot與Kotlin使用Spring-data-jpa簡化數據訪問層
Gradle Kotlin DSL的accessors 生成問題
Kotlin和Swift語言在Redmonk榜上排名大幅提升
Spring Boot與Kotlin 使用MongoDB資料庫
開發 iOS 應用,Kotlin Native 是否夠格?
Kotlin Android 環境搭建
Kotlin 繼承
Kotlin項目下的Retrofit2網路請求框架
Kotlin語言Web庫又添一虎將:Kweb
Kotlin打造Android路由框架
Kotlin 泛型
Kotlin 介面
Kotlin 類和對象
Canonical宣布Kotlin編程語言Snap包格式上線
Google發布Android KTX預覽版,它能為Kotlin開發者做些什麼?
Android開發者是時候轉向Kotlin了
Kotlin 擴展
Kotlin 編程
從源碼角度分析 Kotlin by lazy 的實現
Kotlin 語言獲Linux通行證