Web検索はbingがおすすめ!

定数配列を宣言する - Swift

Swiftで定数配列を宣言するコードを紹介します。

書式

型指定をする場合

let (配列名) : Array<(型名)> = [(値1),(値2),(値3)... (値n)]
または
let (配列名) : [型名] = [(値1),(値2),(値3)... (値n)]

型指定をしない場合

let (配列名) = [(値1),(値2),(値3)... (値n)]

コード例

  let const = [1,2,3,4];
  let const: [Int] = [1,2,3,4];
  let const : Array<Int> = [1,2,3,4];

プログラム

XcodeでiOSのSingle View Application を作成します。

UI

下図のUIを作成します。ButtonとTextViewを配置します。ButtonのTouchDownイベントとTextViewをコードに宣言します。

コード

//
//  ViewController.swift
//  ArrayConstDemo
//
//  Created by Penta on 2016/03/01.
//  Copyright c 2016年 iPentec. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textView1: UITextView!
    
    let Data : Array<String> = ["Penguin", "しろくま", "Duck", "くじら"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        textView1.text="";
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func onButtonDown(sender: AnyObject) {        
        for s in Data {
            textView1.text = textView1.text + s + " ";
        }
    }
}

解説

補足

定数配列のため、宣言した配列に代入するコードはエラーによりコンパイルできません。
下記のコードの場合
    @IBAction func onButtonDown(sender: AnyObject) {
        Data[0]="ペンギン";
        
        for s in Data {
            textView1.text = textView1.text + s + " ";
            
        }
    }

"Cannot assign through subscript: 'Data' is a 'let' constant"
のエラーメッセージが表示されます。


実行結果

プロジェクトを実行します。下図の画面が表示されます。


[Button]をタップします。TextViewにコードで宣言した定数配列の値が表示されます。

著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-07
作成日: 2016-02-15
iPentec all rights reserverd.