extenstionで変数宣言したらExtensions may not contain stored properties

環境

  • swift
  • swift3
  • xcode
  • xcode9
  • Extensions may not contain stored properties
  • struct
  • extension
  • stored properties

説明

Swiftでextensionするときvar宣言するとExtensions may not contain stored propertiesとエラーが出ます。stored propertiesはextensionには宣言できません。つまり、値がある変数は定義できないんです。値のある変数を定義したければ、structを使いましょう。

 

別ファイルにextensionを定義する

スクリーンショット 2017-11-02 15.00.15.png

Extensions.swift
//
//  Extensions with stored properties.swift
//  Extensions with stored properties
//
//  Created by ryosuke-hujisawa on 2017/11/02.
//  Copyright © 2017年 ryosuke-hujisawa. All rights reserved.
//

import Foundation

extension ViewController {

    struct extensionStruct {
        //structの中であればvar定義できる
        var extensionVar = "extensionVarString"
    }
}

ViewControllerから呼び出す

ViewController.swift
//
//  ViewController.swift
//  Extensions with stored properties
//
//  Created by ryosuke-hujisawa on 2017/11/02.
//  Copyright © 2017年 ryosuke-hujisawa. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let instanceStruct = extensionStruct()
        print(instanceStruct.extensionVar)
    }

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

参考

Swiftで構造体とクラスを使い分ける方法(ポイント)
extenstionでの変数宣言

TECHNICAL MASTER はじめてのiOSアプリ開発 第2版 Xcode 8+Swift 3対応【電子書籍】[ 長谷川智希 ]

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事