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?

More than 3 years have passed since last update.

[Swift]Typealiasでコードの可読性を高める

Last updated at Posted at 2021-05-18

はじめに

本文は、以下の記事を参考に作成しています。
[Typealias usage in Swift](Typealias usage in Swift)

Typealiasの用途

コードの可読性を上げることが主な用途です。
変数のデータ型を宣言する際にDoubleIntなどを使用すると思いますが、typealiasを使用することで、DoubleIntなどと同じ機能を持ったエイリアスで宣言することができます。

用途① データ型の代わりにエイリアスで宣言

//通常のデータ型の宣言
struct Receipt {
    let totalCosts: Double
}

//typealiasでDouble型を割り当てたエイリアスDollarを作成
typealias Dollar = Double

// エイリアス`Dollar`で変数を宣言
struct Receipt {
    let totalCosts: Dollar
}

用途② extensionで機能拡張

typealias Dollar = Double
typealias Euro = Double

struct Receipt {
    let totalCosts: Dollar
}

extension Dollar {
    func toEuro() -> Euro {
        return self * 0.896
    }
}

let receipt = Receipt(totalCosts: 10)
receipt.totalCosts.toEuro() // 8.96

let doubleNumber: Double = 10
doubleNumber.toEuro() // 8.96

その他の用途も参考記事に記載されているので、気になる方は見てみてください!

0
1
0

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?