0% found this document useful (0 votes)
112 views8 pages

Swift Is Like Kotlin

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

Swift is like Kotlin

BASICS

Hello World

Swift Kotlin
print("Hello, world!") println("Hello, world!")

Variables And Constants

Swift Kotlin
var myVariable = 42 var myVariable = 42
myVariable = 50 myVariable = 50
let myConstant = 42 val myConstant = 42

Explicit Types

Swift Kotlin
let explicitDouble: Double = 70 val explicitDouble: Double = 70.0

Type Coercion

Swift Kotlin
let label = "The width is " val label = "The width is "
let width = 94 val width = 94
let widthLabel = label + String(width) val widthLabel = label + width
String Interpolation

Kotlin
apples = 3 val apples = 3
oranges = 5 val oranges = 5
fruitSummary = "I have \(apples + oranges) " + val fruitSummary = "I have ${apples + orange
"pieces of fruit." "pieces of fruit."

Range Operator

Kotlin
ames = ["Anna", "Alex", "Brian", "Jack"] val names = arrayOf("Anna", "Alex", "Brian", "J
ount = names.count val count = names.count()
in 0..<count { for (i in 0..count - 1) {
rint("Person \(i + 1) is called \(names[i]) println("Person ${i + 1} is called ${names[
}
rson 1 is called Anna // Person 1 is called Anna
rson 2 is called Alex // Person 2 is called Alex
rson 3 is called Brian // Person 3 is called Brian
rson 4 is called Jack // Person 4 is called Jack

Inclusive Range Operator

Swift Kotlin
for index in 1...5 { for (index in 1..5) {
print("\(index) times 5 is \(index * 5 println("$index times 5 is ${index * 5}")
} }
// 1 times 5 is 5 // 1 times 5 is 5
// 2 times 5 is 10 // 2 times 5 is 10
// 3 times 5 is 15 // 3 times 5 is 15
// 4 times 5 is 20 // 4 times 5 is 20
// 5 times 5 is 25 // 5 times 5 is 25
COLLECTIONS

Arrays

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

Maps

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

Empty Collections

Swift Kotlin
let emptyArray = [String]() val emptyArray = arrayOf<String>()
let emptyDictionary = [String: Float]() val emptyMap = mapOf<String, Float>()

FUNCTIONS

Functions
Kotlin
greet(_ name: String,_ day: String) -> String { fun greet(name: String, day: String): Stri
return "Hello \(name), today is \(day)." return "Hello $name, today is $day."
}
t("Bob", "Tuesday") greet("Bob", "Tuesday")

Tuple Return

Kotlin
getGasPrices() -> (Double, Double, Double) { data class GasPrices(val a: Double, val b: Do
eturn (3.59, 3.69, 3.79) val c: Double)
fun getGasPrices() = GasPrices(3.59, 3.69, 3.

Variable Number Of Arguments

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

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


fun sumOf(vararg numbers: Int) = numbers.sum()

Function Type

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

// makeIncrementer can also be written in a shorter


fun makeIncrementer() = fun(number: Int) = 1 + numbe

Map

Swift Kotlin
let numbers = [20, 19, 7, 12] val numbers = listOf(20, 19, 7, 12)
numbers.map { 3 * $0 } numbers.map { 3 * it }

Sort

Swift Kotlin
var mutableArray = [1, 5, 3, 12, 2] listOf(1, 5, 3, 12, 2).sorted()
mutableArray.sort()

Named Arguments

Swift Kotlin
func area(width: Int, height: Int) -> Int { fun area(width: Int, height: Int) = width * he
return width * height area(width = 2, height = 3)
}
area(width: 2, height: 3) // This is also possible with named arguments
area(2, height = 2)
area(height = 3, width = 2)

CLASSES
Declaration

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

Usage

ft Kotlin
r shape = Shape() var shape = Shape()
ape.numberOfSides = 7 shape.numberOfSides = 7
r shapeDescription = shape.simpleDescription() var shapeDescription = shape.simpleDescript

Subclass

Kotlin
s NamedShape { open class NamedShape(val name: String) {
var numberOfSides: Int = 0 var numberOfSides = 0
let name: String
open fun simpleDescription() =
init(name: String) { "A shape with $numberOfSides sides
self.name = name }
}
class Square(var sideLength: BigDecimal, n
func simpleDescription() -> String { NamedShape(name) {
return "A shape with \(numberOfSides) sides." init {
} numberOfSides = 4
}

s Square: NamedShape { fun area() = sideLength.pow(2)


var sideLength: Double
override fun simpleDescription() =
init(sideLength: Double, name: String) { "A square with sides of length $si
self.sideLength = sideLength }
super.init(name: name)
self.numberOfSides = 4 val test = Square(BigDecimal("5.2"), "squa
} test.area()
test.simpleDescription()
func area() -> Double {
return sideLength * sideLength
}

override func simpleDescription() -> String {


return "A square with sides of length " +
sideLength + "."
}

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


.area()
.simpleDescription()

Checking Type

Swift Kotlin
var movieCount = 0 var movieCount = 0
var songCount = 0 var songCount = 0

for item in library { for (item in library) {


if item is Movie { if (item is Movie) {
movieCount += 1 ++movieCount
} else if item is Song { } else if (item is Song) {
songCount += 1 ++songCount
} }
} }

Pattern Matching

Swift Kotlin
let nb = 42 val nb = 42
switch nb { when (nb) {
case 0...7, 8, 9: print("single digit" in 0..7, 8, 9 -> println("single digit"
case 10: print("double digits") 10 -> println("double digits")
case 11...99: print("double digits") in 11..99 -> println("double digits")
case 100...999: print("triple digits" in 100..999 -> println("triple digits"
default: print("four or more digits" else -> println("four or more digits"
} }

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

Protocol

Swift Kotlin
protocol Nameable { interface Nameable {
func name() -> String fun name(): String
} }

func f<T: Nameable>(x: T) { fun f<T: Nameable>(x: T) {


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

Extensions

Kotlin
ion Double { val Double.km: Double get() = this * 1000
r km: Double { return self * 1_000.0 } val Double.m: Double get() = this
r m: Double { return self } val Double.cm: Double get() = this / 100
r cm: Double { return self / 100.0 } val Double.mm: Double get() = this / 1000
r mm: Double { return self / 1_000.0 } val Double.ft: Double get() = this / 3.28084
r ft: Double { return self / 3.28084 }
val oneInch = 25.4.mm
eInch = 25.4.mm println("One inch is $oneInch meters")
"One inch is \(oneInch) meters") // prints "One inch is 0.0254 meters"
nts "One inch is 0.0254 meters" val threeFeet = 3.0.ft
reeFeet = 3.ft println("Three feet is $threeFeet meters")
"Three feet is \(threeFeet) meters") // prints "Three feet is 0.914399970739201 m
nts "Three feet is 0.914399970739201 meters"

You might also like