質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

966閲覧

Dictionary<String, Any>.Elementの扱い方がわからない

退会済みユーザー

退会済みユーザー

総合スコア0

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2022/12/30 10:34

前提

APIの結果を扱うアプリを作っています。

実現したいこと

Dictionary<String, Any>.Elementの中にある
user = {.. } の中にある screen_nameなどを取得したい。

発生している問題・エラーメッセージ

Cast from 'Dictionary<String, Any>.Element' (aka '(key: String, value: Any)') to unrelated type '[String : Any]' always fails

該当のソースコード

Swift

1Task { 2 let results = try await TwifterClient().search_tweets(q: "#" + self.string()) 3 for result in results { 4 5 if let tttts = result as? [String: Any] { // ←Cast from 'Dictionary<String, Any>.Element' (aka '(key: String, value: Any)') to unrelated type '[String : Any]' always fails 6 for t in tttts { 7 print("--------------------") 8 print(t.key) 9 print(t.value) 10 print("--------------------") 11 } 12 } 13} 14 15
// 返えってくるデータ -------------------- resultは (key: "search_metadata", value: { "completed_in" = "0.08599999999999999"; count = 15; "max_id" = 1608771602052972545; "max_id_str" = 1608771602052972545; "next_results" = "?max_id=1608771173499932675&q=%23elonmusk&include_entities=1"; query = "%23elonmusk"; "refresh_url" = "?since_id=1608771602052972545&q=%23elonmusk&include_entities=1"; "since_id" = 0; "since_id_str" = 0; }) -------------------- -------------------- resultは (key: "statuses", value: <__NSArrayI 0x600000cb7f00>( { contributors = "<null>"; coordinates = "<null>"; "created_at" = "Fri Dec 30 10:26:54 +0000 2022"; entities = { hashtags = ( ); symbols = ( ); urls = ( { "display_url" = "twitter.com/i/web/status/1\U2026"; "expanded_url" = "https://twitter.com/i/web/status/1608771602052972545"; indices = ( 117, 140 ); url = "https://t.co/kZPnC3Li9M"; } ); "user_mentions" = ( ); }; "favorite_count" = 0; favorited = 0; geo = "<null>"; id = 1608771602052972545; "id_str" = 1608771602052972545; "in_reply_to_screen_name" = "<null>"; "in_reply_to_status_id" = "<null>"; "in_reply_to_status_id_str" = "<null>"; "in_reply_to_user_id" = "<null>"; "in_reply_to_user_id_str" = "<null>"; "is_quote_status" = 0; lang = en; metadata = { "iso_language_code" = en; "result_type" = recent; }; place = "<null>"; "possibly_sensitive" = 0; "retweet_count" = 0; retweeted = 0; source = "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>"; text = "The horrifying power of CharGPT. Humans will have lost all control when this starts to control us.\n\nIs Elon Musk pr\U2026 https://t.co/kZPnC3Li9M"; truncated = 1; user = { // ←ここにアクセスしたい "contributors_enabled" = 0; "created_at" = "Tue Nov 22 18:30:07 +0000 2022"; "default_profile" = 1; "default_profile_image" = 0; description = "Sovereignty & Freedom is a birthright (BoR 1689) - Government and science are our servants, not leaders - Always question both - The Truth will set you free"; entities = { description = { urls = ( ); }; url = { urls = ( { "display_url" = "vannigtevecht.com"; "expanded_url" = "http://vannigtevecht.com"; indices = ( 0, 23 ); url = "https://t.co/dzk17g4RIA"; } ); }; }; "favourites_count" = 788; "follow_request_sent" = "<null>"; "followers_count" = 34; following = "<null>"; "friends_count" = 156; "geo_enabled" = 0; "has_extended_profile" = 1; id = 1595122461091270678; "id_str" = 1595122461091270678; "is_translation_enabled" = 0; "is_translator" = 0; lang = "<null>"; "listed_count" = 0; location = "United Kingdom"; name = "Rob van Nigtevecht \Ud83c\Uddec\Ud83c\Udde7"; notifications = "<null>"; "profile_background_color" = F5F8FA; "profile_background_image_url" = "<null>"; "profile_background_image_url_https" = "<null>"; "profile_background_tile" = 0; "profile_banner_url" = "https://pbs.twimg.com/profile_banners/1595122461091270678/1671186606"; "profile_image_url" = "http://pbs.twimg.com/profile_images/1603693160311541767/e5dGSlKN_normal.jpg"; "profile_image_url_https" = "https://pbs.twimg.com/profile_images/1603693160311541767/e5dGSlKN_normal.jpg"; "profile_link_color" = 1DA1F2; "profile_sidebar_border_color" = C0DEED; "profile_sidebar_fill_color" = DDEEF6; "profile_text_color" = 333333; "profile_use_background_image" = 1; protected = 0; "screen_name" = VANNIGTEVECHTR; "statuses_count" = 1172; "time_zone" = "<null>"; "translator_type" = none; url = "https://t.co/dzk17g4RIA"; "utc_offset" = "<null>"; verified = 0; "withheld_in_countries" = ( ); }; }, // ここまでで1個のデータです。

試したこと

1日色々試してみましてがどれもダメでした。
①試したこと: if let ... で値にアクセスしてみる →✖️
https://qiita.com/Atsushi_/items/0dfe56878b269f805c2a

②Keyを探してValueを取得する →✖️
https://qiita.com/Saayaman/items/e82a09f93bb91409e446

③JSONDecoderを使ってDictionary→JSONへ変換
https://stackoverflow.com/questions/68060692/swift-dictionary-api-no-value-associated-with-key-codingkeysstringvalue-typ

JSONへの変換や文字列等の変換を試みてみましたが理解が浅く実現できませんでした。

補足情報(FW/ツールのバージョンなど)

Dictionary<String, Any>.Element自体あまりよくわかっていないのでお手柔らかにお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2022/12/31 05:13

TwifterClientについて私はよく知らないのですが、 こちらについてもどのようなものか質問欄に記載しておいた方が回答がつきやすいかもしれませんね。 オブジェクトの形になっているvalueが全部Anyだとすると valueを取得するごとに[String: Any]にキャストする感じでアクセスできそうですが いかがでしょうか。 ```swift let statuses = results["statuses"] as? NSArray let status = statuses?[0] as? [String: Any] let user = status?["user"] as? [String: Any] print(user?["contributors_enabled"]) // Optional(0) ```
退会済みユーザー

退会済みユーザー

2023/01/02 09:26

ありがとうございます! 無事解決しました。
guest

回答1

0

ベストアンサー

無事解決しました。

Swift

1let statuses = results["statuses"] as? NSArray 2let status = statuses?[0] as? [String: Any] 3let user = status?["user"] as? [String: Any] 4print(user?["screen_name"]) // Optional(TwitterJP)

投稿2023/01/02 09:28

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問