0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift入門④】関数(func)と構造体(struct)を打った

0
Posted at

はじめに

自分用のメモ、というか、学習記録です。
今回は以下を行いました。

  • func関数
    • 入力型固定→出力固定
    • 入力可変→出力固定
    • 入力固定→出力可変
  • struct
    • とりあえず打ってみた位の感覚
    • classとの違いはイマイチわかっていない・・・

関数(func)について

1. 入力型固定→出力型固定

最も基本的な関数の形です。引数と戻り値の型を明示的に指定します。

print("===func===")
// 入力型固定→出力型固定
func TEST(person: String) -> String {
    return "こんにちは \(person)です。"
}

let message = TEST(person: "田中")
print(message)

2. 入力型可変→出力型固定

2と後続の3は、すこしイレギュラーなものをやりました。

// 入力が可変→出力型固定
// 型が自由だから、Tはなんでも型はいいので、共有して使うイメージ。
// ただし、Tは同じ型でなくてはならない!!!!
func getDescription<T>(value: T, error: T) -> String {
    return "入力された値は \(value)\(error)です"
}
print(getDescription(value: 100, error: 200))
//print(getDescription(value: "こんにちは", error: 100)) //エラーが起きる
print(getDescription(value: true, error: false))

3. 入力型固定→出力型可変

// 入力は固定→出力が柔軟
enum Result {
    case success(String)
    case failure(Int)
    case unknown(Bool)
}

func fetchData (id: Int) -> Result {
    if id == 1 {
        return .success("田中太郎")
    } else if id == 404 {
        return .failure(404)
    } else {
        return .unknown(true)
    }
}

let myResult = fetchData(id: 999)

switch myResult {
case .success(let name):
    print(name)
case .failure(let code):
    print(code)
case .unknown(let boolian):
    print(boolian)
}

構造体(struct)について

print("===Structと構造===")

struct User {
    var NAME: String
    var AGE: Int
    
    func sayHello() {
        print("私の名前は\(NAME)です")
    }
}

let user1 = User(NAME: "佐藤", AGE: 27)
user1.sayHello()

structの特徴

  • プロパティ(変数)とメソッド(関数)をまとめて管理できる
  • イニシャライザが自動生成される
  • 値型(コピーされる)として動作する
  • 他の言語でいうクラスに似た概念

まとめ

  • 関数の型指定: 引数と戻り値の型を固定・柔軟に設定できる
  • ジェネリクス: <T>を使って型を柔軟に扱える(ただし同じ型である必要がある)
  • enum: 複数の異なる型の戻り値を扱える
  • struct: データとメソッドをまとめて管理できる便利な構造

次回

とりあえず、UI作るぞ!!

参考にする予定の記事

参考

  • Geminiとの対話
0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?