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

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

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

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

Swift 2

Swift 2は、Apple社が独自に開発を行っている言語「Swift」のアップグレード版です。iOSやOS X、さらにLinuxにも対応可能です。また、throws-catchベースのエラーハンドリングが追加されています。

Q&A

解決済

2回答

1351閲覧

プログラミング言語のSwihtについて質問です。

damadama

総合スコア7

Swift

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

Swift 2

Swift 2は、Apple社が独自に開発を行っている言語「Swift」のアップグレード版です。iOSやOS X、さらにLinuxにも対応可能です。また、throws-catchベースのエラーハンドリングが追加されています。

0グッド

0クリップ

投稿2016/08/12 12:11

プログラミング言語のSwihtについて質問です。

最近、独学で始めたのですが、少しDictionary型のところで行き詰まりました。
このソースコードに対して↓
//dictionaryを定義して、keyを指定してvalueを取得する
let dic = ["key": "バリュー"]
print(dic["key"])

こう結果が帰ってきます↓
Optional("バリュー")

「!」や「?」をつけていないのに、なぜOptinalになるのでしょうか?
教えてください。

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

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

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

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

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

guest

回答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
_Kentarou

総合スコア8490

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

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

damadama

2016/08/12 16:02

とても詳しくて、参考になりました!! ありがとうございました。
guest

0

なぜoptionalが返るのかと言えば、
「そういう仕様だから」

なぜそういう仕様かと言えば、
恐らく
存在しないキーに対してnilを返したいからです

投稿2016/08/12 12:36

ozwk

総合スコア13521

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

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

damadama

2016/08/12 16:05

そいう仕様なのですね!! 答えて頂き、ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問