Help us understand the problem. What is going on with this article?

Swift の Optional と Kotlin の Nullable

業務の中で iOS と Android のPRの両方をレビューしていて、SwiftKotlin とで Type safe な書き方の呼び方が違うよねって話題に上がったので忘備録的な感じで書いています。

呼び方の違い

Swift

Optional

var name: String?
または
var name: Optional<String>

Apple Developer Documentation - Optional

Kotlin

Nullable
(Java の Optional とは別物)

var name: String?

Type safe な書き方の違い

iOS Developper なので Swift ベースで書いています。
Swift での呼び方、書き方はこうだけど、 Kotlin ではこう書くよ的な。

Optional Binding (Swift)

var name: String?
if let aName = name {
  print(aName.uppercased())
} else {
  print("`name` is nil.")
}

THE SWIFT PROGRAMMING LANGUAGE / The Basics - Optional Binding

Kotlin の場合

呼び方: Checking for null in conditions
(Kotlin に詳しい人はなんて呼んでいるんでしょうね・・・)

var name: String?
if (name != null) {
  print(name.toUpperCase())
} else {
  print("`name` is null.")
}

KOTLIN PROGRAMMING LANGUAGE / Null Safety - Checking for null in conditions

Optional Chaining (Swift)

var name: String?
let count = name?.count
print(count)

THE SWIFT PROGRAMMING LANGUAGE / Optional Chaining

Kotlin の場合

呼び方: Safe Calls

var name: String?
val length = name?.length
print(length)

KOTLIN PROGRAMMING LANGUAGE / Null Safety - Safe Calls

Forced Unwrapping (Swift)

var name: String?
let count = name!.count
print(count)

THE SWIFT PROGRAMMING LANGUAGE / The Basics - If Statements and Forced Unwrapping

Kotlin の場合

呼び方: !! Operator (Non-null Operator)
※人によっては呼び方が変わってくるかもです

var name: String?
val length = name!!.length
print(length)

KOTLIN PROGRAMMING LANGUAGE / Null Safety - The !! Operator

Nil-Coalescing Operator (Swift)

var name: String?
let aName = name ?? "Swift"
print(aName)

THE SWIFT PROGRAMMING LANGUAGE / Basic Operators - Nil-Coalescing Operator

Kotlin の場合

呼び方: Elvis Operator

var name: String?
val aName = name ?: "Kotlin"
print(aName)

KOTLIN PROGRAMMING LANGUAGE / Null Safety - Elvis Operator

dacchan
iOS アプリ開発者。 https://github.com/dacchan/Swiftensions 作ってます。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした