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.

`Cannot find 'JSONEncoder' in scope` の対処

Last updated at Posted at 2021-06-03

Cannot find 'JSONEncoder' in scopeというエラーの対処

あまりに初歩的ゆえに、なかなか見つからず困ったのでメモ。

##環境

プログラム バージョン
Xcode Version 12.5
swift Version 5.4

##状況
Jsonのエンコード・デコードのやり方を調べるためにApple Developer Documentation に記載されている通り、以下のコードをプレイグラウンドで実行したところJSONEncoderのところでエラーが出た。

MyPlayground.playground
struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")

let encoder = JSONEncoder() // エラー:Cannot find 'JSONEncoder' in scope
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)

原因

フレームワークをインポートしていない。

対処

import Foundation

を先頭に追加。
ちなみに、frameworkはApple Developer Documentationの右側にAvailabilityなどと一緒に記載されている。

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?