0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlinの文法の基礎(Swiftとの比較)

Posted at

はじめに

いままで仕事でSwiftしか使ってこなかったですがAndroidもやることになったので,Swiftと比較しながら調べてみました。

1. 変数と定数

Kotlin

val constant: Int = 10 // 定数
var variable: Int = 5 // 変数

Swift

let constant: Int = 10 // 定数
var variable: Int = 5 // 変数

2. 関数

Kotlin

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

Swift

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

3. クロージャ

Kotlin

Kotlinのラムダ式は、無名関数やクロージャに相当します。

val sum: (Int, Int) -> Int = { a, b -> a + b }
println(sum(5, 3)) // 8

Swift

let sum: (Int, Int) -> Int = { a, b in
    return a + b
}
print(sum(5, 3)) // 8

4. if

Kotlin

val max = if (a > b) a else b

Swift

let max = (a > b) ? a : b

5. when文(Kotlinのswitchに相当)

Kotlin

when (x) {
    1 -> println("x is 1")
    2 -> println("x is 2")
    else -> println("x is not 1 or 2")
}

Swift

switch x {
case 1:
    print("x is 1")
case 2:
    print("x is 2")
default:
    print("x is not 1 or 2")
}

6. クラスとオブジェクト

Kotlin

class Person(val name: String, var age: Int) {
    fun introduce() {
        println("My name is $name and I am $age years old.")
    }
}

val person = Person("Alice", 25)
person.introduce()

Swift

class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func introduce() {
        print("My name is \(name) and I am \(age) years old.")
    }
}

let person = Person(name: "Alice", age: 25)
person.introduce()

7. Nullable型

Kotlin

Kotlinでは、nullを扱うためにNullable型があります。

var name: String? = null
name = "Bob"

Swift

Swiftでは、オプショナルを使用してnullを扱います。

var name: String? = nil
name = "Bob"

8. ラムダ式の引数

Kotlin

fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

val result = calculate(5, 3, { x, y -> x + y })

Swift

func calculate(a: Int, b: Int, operation: (Int, Int) -> Int) -> Int {
    return operation(a, b)
}

let result = calculate(5, 3) { x, y in x + y }

9. 拡張関数

Kotlin

fun String.addExclamation() = this + "!"
println("Hello".addExclamation()) // Hello!

Swift

extension String {
    func addExclamation() -> String {
        return self + "!"
    }
}

print("Hello".addExclamation()) // Hello!
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?