プログラミング言語のSwihtについて質問です。
最近、独学で始めたのですが、少しDictionary型のところで行き詰まりました。
このソースコードに対して↓
//dictionaryを定義して、keyを指定してvalueを取得する
let dic = ["key": "バリュー"]
print(dic["key"])
こう結果が帰ってきます↓
Optional("バリュー")
「!」や「?」をつけていないのに、なぜOptinalになるのでしょうか?
教えてください。
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
回答2件
0
ベストアンサー
上記のコードは省略した形で型を書くと以下のようになります。
swift
1let dic: Dictionary<String,String> = ["key": "バリュー"]
これはDictionary
という構造体(struct
)でキーがString
,値がString
になります。
Dictionary
の定義に飛んでみると(⌘ + Dictionaryをクリック
またはDictionaryを選択 → 右クリック → Jump to Difinition
)以下の様なコードがあると思います。
swift
1public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible { 2 public typealias Element = (Key, Value) 3 public typealias Index = DictionaryIndex<Key, Value> 4 /// Create an empty dictionary. 5 public init() 6 /// Create a dictionary with at least the given number of 7 /// elements worth of storage. The actual capacity will be the 8 /// smallest power of 2 that's >= `minimumCapacity`. 9 public init(minimumCapacity: Int) 10 /// The position of the first element in a non-empty dictionary. 11 /// 12 /// Identical to `endIndex` in an empty dictionary. 13 /// 14 /// - Complexity: Amortized O(1) if `self` does not wrap a bridged 15 /// `NSDictionary`, O(N) otherwise. 16 public var startIndex: DictionaryIndex<Key, Value> { get } 17 /// The collection's "past the end" position. 18 /// 19 /// `endIndex` is not a valid argument to `subscript`, and is always 20 /// reachable from `startIndex` by zero or more applications of 21 /// `successor()`. 22 /// 23 /// - Complexity: Amortized O(1) if `self` does not wrap a bridged 24 /// `NSDictionary`, O(N) otherwise. 25 public var endIndex: DictionaryIndex<Key, Value> { get } 26 /// Returns the `Index` for the given key, or `nil` if the key is not 27 /// present in the dictionary. 28 @warn_unused_result 29 public func indexForKey(key: Key) -> DictionaryIndex<Key, Value>? 30 /// Access the key-value pair at `position`. 31 /// 32 /// - Complexity: O(1). 33 public subscript (position: DictionaryIndex<Key, Value>) -> (Key, Value) { get } 34 /// Access the value associated with the given key. 35 /// 36 /// Reading a key that is not present in `self` yields `nil`. 37 /// Writing `nil` as the value for a given key erases that key from 38 /// `self`. 39 public subscript (key: Key) -> Value? 40 41 42 //........
※まだまだありますが、必要なところまで抽出
今回重要なのが以下のコードでsubscript
といい添字アクセス
(dic["key"]
の様な記述)を可能にするメソッドです。
swift
1public subscript (key: Key) -> Value?
そしてこのValue
値の戻り値がoptional
になっている為Optional("バリュー")
と表示されるという事です。
Dictionary
はキーに対して必ず値があるとは限らないのでこの様になっています。
subscript
は自身が定義したクラスにも使えますので勉強してみると面白いです。
参考URL: Swift の Subscript について
投稿2016/08/12 15:08
編集2016/08/12 15:09総合スコア8490
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/08/12 16:02