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.
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.
No package. Swift uses frameworks for namespacing purposes.
Requires the main function
Requires no main function
First, they diff in the function declaration keyword (fun for kotlin, func for swift), and return type indication symbol (: for kotlin, '->` for swift)
fun sum(a: Int, b: Int): Int {
return a + b
}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 + bThird, 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.
fun sum(a: Int, b: Int) = a + bfunc 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.
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.
// 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// 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 += 1Both 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.
/**
* 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 { ... }
}/**
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 { ... }Both language supports string interpolation. Kotlin use $variable or $(expr), whereas Swift use \(variable) or \(expr)
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"
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)"Similar in its basic usage form, but differ more in other usage cases.
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}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,
ifcan be used as an expression, such asfun maxOf(a: Int, b: Int) = if (a > b) a else b. This is not available in Swift. - Swift provides
if letbinding (e.g.,if let resp = getResponse() {}, which Kotlin does not support. - Swift provides
if casepattern matching (e.g.,if case let (x, y) = point {}), which Kotlin does not support.
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
NullableasC#, whereas Swift usesOptionalas other languages, e.g., Java. - Kotlin uses 'null' to indicate null value, and Swift uses
nilto indicate none value
var data: String? = null
fun parseInt(str: String): Int? {
// ...
}var data: String? = nil
func parseInt(str: String) -> Int? {
// ...
}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
}for loop while repeat while
when switch