17
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift の Optional と Kotlin の Nullable

Last updated at Posted at 2019-08-19

業務の中で 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

17
9
3

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
17
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?