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" 原文地址:https://www.oschina.net/news/85013/swift-is-like-kotlin?from=groupmessage&isappinstalled=1
Swift 与 Kotlin 的简单对比的更多相关文章
- [Android开发学iOS系列] 语言篇: Swift vs Kotlin
Swift vs Kotlin 这篇文章是想着帮助Android开发快速学习Swift编程语言用的. (因为这个文章的作者立场就是这样.) 我不想写一个非常长, 非常详尽的文章, 只是想写一个快速的版 ...
- MongoDB中insert方法、update方法、save方法简单对比
MongoDB中insert方法.update方法.save方法简单对比 1.update方法 该方法用于更新数据,是对文档中的数据进行更新,改变则更新,没改变则不变. 2.insert方法 该方法用 ...
- .NET轻量级MVC框架:Nancy入门教程(二)——Nancy和MVC的简单对比
在上一篇的.NET轻量级MVC框架:Nancy入门教程(一)——初识Nancy中,简单介绍了Nancy,并写了一个Hello,world.看到大家的评论,都在问Nancy的优势在哪里?和微软的MVC比 ...
- HTTPS, SPDY和 HTTP/2性能的简单对比
中文原文:HTTPS, SPDY和 HTTP/2性能的简单对比 整理自:A Simple Performance Comparison of HTTPS, SPDY and HTTP/2 请尊重版权, ...
- Swift学习--闭包的简单使用(三)
一.Swift中闭包的简单使用 override func viewDidLoad() { super.viewDidLoad() /** 闭包和OC中的Block非常相似 OC中的block类似于匿 ...
- 【转贴】Cortex系列M0-4简单对比
转载网址:http://blog.sina.com.cn/s/blog_7dbd9c0e01018e4l.html 最近搞了块ST的Cortex-M4处理器,然后下了本文档.分享一下. 针对目前进入大 ...
- 简单对比Spark和Storm
2013年参与开发了一个类似storm的自研系统, 2014年使用过spark 4个多月,对这两个系统都有一些了解. 下面是我关于这两个系统的简单对比: Spark: 1. 基于数据并行,https: ...
- Nancy和MVC的简单对比
Nancy和MVC的简单对比 在上一篇的.NET轻量级MVC框架:Nancy入门教程(一)——初识Nancy中,简单介绍了Nancy,并写了一个Hello,world.看到大家的评论,都在问Nancy ...
- [评测]低配环境下,PostgresQL和Mysql读写性能简单对比(欢迎大家提出Mysql优化意见)
[评测]低配环境下,PostgresQL和Mysql读写性能简单对比 原文链接:https://www.cnblogs.com/blog5277/p/10658426.html 原文作者:博客园--曲 ...
随机推荐
- Xcode 9 打印信息解决
Xcode 9 打印信息解决 打印信息 1 nw_proxy_resolver_create_parsed_array PAC evaluation error: kCFErrorDomainCFNe ...
- RGB、YUV和YCbCr介绍【转】
RGB: 就是常说的红(Red).绿(Green)和蓝(Blue),每个图像的像素点由RGB三个通道的值组成. YUV和YCbCr: YUV与RGB的转换: Y'= 0.299*R' + 0.587* ...
- C#斐波那契数列递归算法
public static int Foo(int i) { if (i < 3) { return 1; ...
- hystrix 解决服务雪崩效应
1.服务雪崩效应 默认情况下tomcat只有一个线程池去处理客户端发送的所有服务请求,这样的话在高并发情况下,如果客户端所有的请求堆积到同一个服务接口上, 就会产生tomcat的所有线程去处理该服务接 ...
- 第一节、ES6的开发环境搭建
https://blog.csdn.net/zls986992484/article/details/70819462 下面这个不好使 https://blog.csdn.net/gao5311624 ...
- Day 14A 网络编程入门
---恢复内容开始--- 计算机网络基础 计算机网络是独立自主的计算机互联而成的系统的总称,组建计算机网络最主要的目的是实现多台计算机之间的通信和资源共享.今天计算机网络中的设备和计算机网络的用户已经 ...
- pycharm connect to mysql
1.download mysql installer community 5.7.20 https://dev.mysql.com/downloads/file/?id=473605 or 链接:ht ...
- RNN,LSTM,GRU基本原理的个人理解
记录一下对RNN,LSTM,GRU基本原理(正向过程以及简单的反向过程)的个人理解 RNN Recurrent Neural Networks,循环神经网络 (注意区别于recursive neura ...
- git命令初级
git是开源的分布式版本控制系统,分布式主要区别于集中式代表CVS(Concurrent Version System,遵从C/S架构,同步比较笨拙.)和SVN(Subversion),linux开发 ...
- python中基于tcp协议的通信(数据传输)
tcp协议:流式协议(以数据流的形式通信传输).安全协议(收发信息都需收到确认信息才能完成收发,是一种双向通道的通信) tcp协议在OSI七层协议中属于传输层,它上承用户层的数据收发,下启网络层.数据 ...