Swift 就像 Kotlin?看看 Swift 与 Kotlin 的简单对比

一位国外的程序员认为 Swift 的语法与 Kotlin 相似,并整理了一些 Swift 和 Kotlin 的对比,下面是一些例子,大家不妨也看看。

BASICS

Hello World

Swift

print("Hello, world!")

Kotlin

println("Hello, world!")

变量和常量

Swift

var myVariable = 42
myVariable = 50
let myConstant = 42

Kotlin

var myVariable = 42
myVariable = 50
val myConstant = 42

显式类型

Swift

let explicitDouble: Double = 70

Kotlin

val explicitDouble: Double = 70.0

强制类型转换

Swift

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

Kotlin

val label = "The width is "
val width = 94
val widthLabel = label + width

字符串插值

Swift

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

Kotlin

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

范围操作符

Swift

let names = ["Anna", "Alex", "Brian", "Jack"]
let 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

Kotlin

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

包罗广泛的范围操作符(Inclusive Range Operator)

Swift

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

Kotlin

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

BASICS

数组

Swift

var shoppingList = ["catfish", "water",
    "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

Kotlin

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

映射

Swift

var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

Kotlin

val occupations = mutableMapOf(
    "Malcolm" to "Captain",
    "Kaylee" to "Mechanic"
)
occupations["Jayne"] = "Public Relations"

空集合

Swift

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

Kotlin

val emptyArray = arrayOf<String>()
val emptyMap = mapOf<String, Float>()

FUNCTIONS

函数

Swift

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

Kotlin

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

元组返回

Swift

func getGasPrices() -> (Double, Double, Double) {
    return (3.59, 3.69, 3.79)
}

Kotlin

data class GasPrices(val a: Double, val b: Double,
     val c: Double)
fun getGasPrices() = GasPrices(3.59, 3.69, 3.79)

参数的变量数目(Variable Number Of Arguments)

Swift

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

Kotlin

fun sumOf(vararg numbers: Int): Int {
    var sum = 0
    for (number in numbers) {
        sum += number
    }
    return sum
}
sumOf(42, 597, 12)

// sumOf() can also be written in a shorter way:
fun sumOf(vararg numbers: Int) = numbers.sum()

函数类型

Swift

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

Kotlin

fun makeIncrementer(): (Int) -> Int {
    val addOne = fun(number: Int): Int {
        return 1 + number
    }
    return addOne
}
val increment = makeIncrementer()
increment(7)

// makeIncrementer can also be written in a shorter way:
fun makeIncrementer() = fun(number: Int) = 1 + number

映射

Swift

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

Kotlin

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

排序

Swift

var mutableArray = [1, 5, 3, 12, 2]
mutableArray.sort()

Kotlin

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

命名参数

Swift

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

Kotlin

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)

CLASSES

声明

Swift

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

Kotlin

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

用法

Swift

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

Kotlin

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

子类

Swift

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

Kotlin

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

类型检查

Swift

var movieCount = 0
var songCount = 0

for item in library {
    if item is Movie {
        movieCount += 1
    } else if item is Song {
        songCount += 1
    }
}

Kotlin

var movieCount = 0
var songCount = 0

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

模式匹配

Swift

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")
}

Kotlin

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")
}

类型向下转换

Swift

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

Kotlin

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

协议

Swift

protocol Nameable {
    func name() -> String
}

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

Kotlin

interface Nameable {
    fun name(): String
}

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

扩展

Swift

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")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"

Kotlin

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")
// prints "One inch is 0.0254 meters"
val threeFeet = 3.0.ft
println("Three feet is $threeFeet meters")
// prints "Three feet is 0.914399970739201 meters"

本文来自开源中国社区 [http://www.oschina.net]

时间: 2024-10-19 02:08:01

Swift 就像 Kotlin?看看 Swift 与 Kotlin 的简单对比的相关文章

swift语言实战晋级-1 Swift开发环境的搭建

原文:swift语言实战晋级-1 Swift开发环境的搭建     想要进行Swift的学习,必须要有个开发环境.简单的说就是装好了Xcode的Mac系统.那么接下来我们就简单了解一下这方面的内容.   1.1 下载Xcode        Xcode是苹果公司出的编程工具,类似于微软出品的visual studio,编写Java的eclipse,开发Flash的Flash IDE.所谓工欲善其事必先利其器,所以我们首先要知道的事情就是该去哪里下载Xcode,有以下几个途径.        途径

Swift与Objective C的简单对比_Swift

现在Swift和Objective C的竞争正在飞快加剧. 这是很容易理解的,因为他们都有各自的好处,一些开发人员对对如何选择一个适合项目的编程语言产生了困惑. 首先,这两者之间的选择是没有严格的答案.在做出选择之前,要考虑很多事情,包括各种因素和特征.各自缺点和优点. 因此,这里做一个概述,以客观展示双方之间的差异和利弊,因为我们认为明智的做法是选择根据是否适合自己的开发团队和具体项目进行选择. 管理考虑 第一个考虑是根据特定团队选择.即使Swift通常被称为更简单,更平滑的语法语言,它消除了

Swift 正式开源, 包括 Swift 核心库和包管理器

Swift 正式开源!Swift 团队很高兴宣布 Swift 开始开源新篇章.自从苹果发布 Swfit 编程语言,就成为了历史上发展最快的编程语言之一.Swift 通过设计使得软件编写更加快速更加安全. Swift 的 GitHub 地址:https://github.com/apple/swift Swift 是由多种不同的项目组成的,提供一个构建软件的完整生态系统.Swift 编译器项目解析 Swift 语法,产生语义判断来帮助编写正确代码,利用 LLVM 生成机器指令.LLDB 项目是 f

swift学习:第一个swift程序

原文:swift学习:第一个swift程序 最近swift有点火,赶紧跟上学习.于是,个人第一个swift程序诞生了...   新建项目   选择ios应用,单视图应用   随便起个项目名称,语言选择"swift"   项目建好了,我们这里只需要在AppDelegate.swift文件里加上几行代码就ok   你会看到下面这个方法.从注释可以看出,应用加载后就会运行这个方法 func application(application: UIApplication, didFinishLa

Swift学习第一练——用Swift实现的FlappyBird小游戏

用Swift实现的FlappyBird小游戏       伴随着apple公司对swift的推广态度深入,swift火的很快,并且swift精简便捷的语法和强大的功能,对于使用Object-C开发iOS的开发者来说,也有必要了解学习一下swift.这篇博客跳过swift干涩的语法,直接从一个小游戏项目开始使用swift,将其中收获总结如下:     FlappyBird是前段时间很火的一款小游戏,通过手指点击屏幕平衡小鸟通过障碍.我是将以前OC版的项目拿来改成了swift,所以整体的思路还是OC

swift学习:第一个swift ui程序

最近swift有点火,赶紧跟上学习.于是,个人第一个swift程序诞生了...   新建项目   选择ios应用,单视图应用   随便起个项目名称,语言选择"swift"   项目建好了,我们这里只需要在AppDelegate.swift文件里加上几行代码就ok   你会看到下面这个方法.从注释可以看出,应用加载后就会运行这个方法 func application(application: UIApplication, didFinishLaunchingWithOptions lau

对 Kotlin 的期待 关于 Kotlin 未来功能的调查结果

今日,Kotlin 在其官方博客发表了一篇关于其未来功能调查结果的报告,这份调查于 4 月份开始.下面简要介绍一下报告中的内容. 官方表示,因为最近发生了很多激动人心的事,所以不得不推迟发表关于 Kotlin 未来功能的调查结果,并对此感到十分抱歉.不过迟到总比不到好,这篇博客总结了从调查中学到的内容. 关于未来功能的调查在四月份已经开始了,总共收到了 850 份的回复. 调查结果 调查的原始数据(匿名)可在这里获取. 调查的问题是: 最期待的功能1,最期待的功能2,最期待的功能3 写出一个希望

Swift 2.x 升为 swift 3后语法不兼容问题适配

[解决方法]设置 Build Settings --> Use Legacy Swift Language Version --> 改为YES

【swift学习笔记】四.swift使用Alamofire和swiftyJson

Alamofire是AFNetworking的swift版本,功能灰常强大. github:https://github.com/Alamofire/Alamofire SwiftyJSON是操作json的非常棒的开源库 github:https://github.com/SwiftyJSON/SwiftyJSON 接下来我做一个简单的入门小例子, 我使用cocoaPods来管理依赖,需要在Podfile里添加我们需要的两个库 source 'https://github.com/CocoaPo