LoginSignup
2
3

More than 5 years have passed since last update.

NotNull宣言したプロパティは文字列リテラルの中でOptionalになる

Last updated at Posted at 2016-10-03

まずは普通に


class Model {
  var value: Int
  init(value: Int) {
    self.value = value
  }
}

let model = Model(value: 0)
print("\(model.value)")

結果は
0

ではプロパティを明示的にNotNullと宣言する


class Model2 {
  var value: Int!
  init(value: Int) {
    self.value = value
  }
}


let model = Model2(value: 0)
print("\(model.value)")

結果は

Optional(0)

追記

Apple Swift version 3.0 (swiftlang-800.0.46.2 clang-800.0.38)
Target: x86_64-apple-macosx10.9
/Applications/Xcode8.app/Contents/Developer/usr/bin/lldb "--repl=-target x86_64-apple-macosx10.9 -enable-objc-interop -sdk /Applications/Xcode8.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -color-diagnostics"
Welcome to Apple Swift version 3.0 (swiftlang-800.0.46.2 clang-800.0.38). Type :help for assistance.
  1> class Model2 {
  2.   var value: Int!
  3.   init(value: Int) {
  4.     self.value = value
  5.   }
  6. }
  7.
  8.
  9. let model = Model2(value: 0)
 10. print("\(model.value)")
Optional(0)
Apple Swift version 2.2 (swiftlang-703.0.18.1 clang-703.0.29)
Target: x86_64-apple-macosx10.9
/Applications/Xcode.app/Contents/Developer/usr/bin/lldb "--repl=-target x86_64-apple-macosx10.9 -enable-objc-interop -sdk /Applications/Xcode8.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -color-diagnostics"
Welcome to Apple Swift version 2.2 (swiftlang-703.0.18.1 clang-703.0.29). Type :help for assistance.
  1> class Model2 {
  2.   var value: Int!
  3.   init(value: Int) {
  4.     self.value = value
  5.   }
  6. }
  7.
  8.
  9. let model = Model2(value: 0)
 10. print("\(model.value)")
0

Swift3からみたい

2
3
2

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
2
3