Skip to content

Instantly share code, notes, and snippets.

@nn1900
Last active November 6, 2019 17:11
Show Gist options
  • Save nn1900/41758e78f9432fcd8857d4eaf11bc7e8 to your computer and use it in GitHub Desktop.
Save nn1900/41758e78f9432fcd8857d4eaf11bc7e8 to your computer and use it in GitHub Desktop.
comparison between swift and kotlin

Swift v.s. Kotlin

Swift and Kotlin are very similar in many aspects. However, they also have many differences. This documentation describes these similarities and differences between them by considering the language constructs they have.

1. Package

Kotlin

Package specification should be at the top of the source file. Unlike Java, however, it is not required to match directories and packages, i.e., source files can be placed arbitrarily in the file system.

Swift

No package. Swift uses frameworks for namespacing purposes.

2. Program entry point

Kotlin

Requires the main function

Swift

Requires no main function

3. Function declaration

First, they diff in the function declaration keyword (fun for kotlin, func for swift), and return type indication symbol (: for kotlin, '->` for swift)

Kotlin

fun sum(a: Int, b: Int): Int {
  return a + b
}

Swift

func sum(a: Int, b: Int) -> Int {
  return a + b
}

Second, Kotlin provides shorthand function declaration as below which has no counterpart in Swift:

fun sum(a: Int, b: Int) = a + b

Third, Function's return type can be inferred in Kotlin if the function contains only expressions and must be explicitly specified in Swift, even though return type for functions that does not return anything can be omitted in both languages.

Kotlin

fun sum(a: Int, b: Int) = a + b

Swift

func sum(a: Int, b: Int) -> Int {
  return a + b
}

Both languages distinguish the semantics between return nothing and never returns. Kotlin use Unit and Nothing, and Swift use Void (or an empty tuple ()) and Never to indicate these two semantics correspondingly. Further more, these return types can be omitted in the function declaration in both languages.

4. Variables

Both languages have the concepts of readonly variable and mutable variable at the language level. Kotlin use val and var, and Swift use let and var correspondingly. And in both languages, global readonly variables must be initialized when declarared, and local readonly variables initialization can be deferred before first used.

Kotlin

// readonly variables
val: a: Int = 1
val b = 2
val c: Int // requires initialization in global context
c = 3

// mutable variables
var x = 4
x += 1

Swift

// readonly variables
let: a: Int = 1
let b = 2
let c: Int // requires initialization in global context
c = 3

// mutable variables
var x = 4
x += 1

5. Comments

Both language supports single-line comment // .... and block (multi-line) /* ... */ comment. In addition, Kotlin follows KDoc for documentation and Swift use XCode Markup Formatting something similar to Markdown but with some extensions.

Kotlin

/**
 * A group of *members*.
 *
 * This class has no useful logic; it's just a documentation example.
 *
 * @param T the type of a member in this group.
 * @property name the name of this group.
 * @constructor Creates an empty group.
 */
class Group<T>(val name: String) {
    /**
     * Adds a [member] to this group.
     * @return the new size of the group.
     */
    fun add(member: T): Int { ... }
}

Swift

/**
  Some description
 
     - important: Make sure you read this
     - returns: a Llama spotter rating between 0 and 1 as a Float
     - parameter totalLlamas: The number of Llamas spotted on the trip
 
 Find more information for [Swift](http://swift.org)
 
 *Values*
 
  `NegativeCount` The count is less than 0.
 
  `EmptyString1` The first string argument is empty.
 
  `EmptyString2` The second string argument is empty.
 
  - Author:
    Newbie
  - Version:
    0.1
 */
func add<T>(member: T> -> Int { ... }

6. String templates/interpolation

Both language supports string interpolation. Kotlin use $variable or $(expr), whereas Swift use \(variable) or \(expr)

Kotlin

var a = 1

// simple name in template:
val s1 = "a is $a"

// arbitrary expression in template:
a = 2
val s2 = "${s1.replace("is", "was")}, but now is $a"

Swift

var a = 1

// simple name in template:
let s1 = "a is \(a)"

// arbitrary expression in template:
a = 2
let s2 = "\(s1.replacingOccurrences(of: "is", with: "was")), but now is \(a)"

7. Conditional Expression

Similar in its basic usage form, but differ more in other usage cases.

Kotlin

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

Swift

func maxOf(a: Int, b: Int)-> Int {
    // parathesis can be used around the conditional expression, and is not recommended
    if a > b { 
        return a
    } else {
        return b
    }
}

Differences:

  • In Kotlin, if can be used as an expression, such as fun maxOf(a: Int, b: Int) = if (a > b) a else b. This is not available in Swift.
  • Swift provides if let binding (e.g., if let resp = getResponse() {}, which Kotlin does not support.
  • Swift provides if case pattern matching (e.g., if case let (x, y) = point {}), which Kotlin does not support.

8. Nullable/Optional values and null checks

Both languages provide explicit support for nullable types and values and related facilities at the language level (Java introduced Optional since Java 9). Each variable or property that can be null/nil must be marked explicitly to accept null or nil.

  • They both use the form T? to declare the nullable/optional type
  • Kotlin uses the term Nullable as C#, whereas Swift uses Optional as other languages, e.g., Java.
  • Kotlin uses 'null' to indicate null value, and Swift uses nil to indicate none value

Kotlin

var data: String? = null
fun parseInt(str: String): Int? {
   // ...
}

Swift

var data: String? = nil
func parseInt(str: String) -> Int? {
   // ...
}

9. Type checks and automatic casts

In Kotlin, the is operator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a specific type, there's no need to cast it explicitly. This is also known as Smart Cast.

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}

10. Loops

for loop while repeat while

11. Switch

when switch

12. Ranges

13. Collections

14. Closure/Lambda Expressions

15. Enum

16. Struct

17. Class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment