LoginSignup
1
1

More than 5 years have passed since last update.

Swift4でのreflection

Last updated at Posted at 2018-02-10

Swift3.X → Swift4.X 移行の時に
reflectionを使っているところで以下のようなビルドエラーが出て困る。
"this class is not key value coding-compliant for the key Name."
"This class is not key value coding compliant"

具体的なソースでいうとたぶんこんな感じのところ

class Person : NSObject
{
    var Name:String = ""
}

let taro = Person()
taro.setValue("山田太郎", forKey: "Name") <<<<<ここでエラー!!

と、setValueで値を格納しているところで上記のようなエラーが出ると思う。
解決策だけさらっと書くと

@objcMembers class Person : NSObject
{
    var Name:String = ""
}

のように、"@objcMembers"をclass定義の頭につけてやる。
Objective-Cから離れたいのになぜか離れられないSwift、中の人は何か苦労があるんだろうな・・・

Swift4からはJsonのエンコードではCodableが使えるようになったのでリフレクションを使う場面は少し減るかも。

参考

Swift reflectionについて

Codableで色々なJSONに対応する

1
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
1
1