A type that represents either a wrapped value or nil, the absence of a value. swift types can be optianl , which is indicated by appending ? to a type name
let shortForm: Int ? = Int("42")
let longForm: Optinal<Int> = Int("42")
The Optinal type is an enumeration with two cases
nil literal let number : Int ? = Optional.some(42)
let noNumber: Int? = Optional.none
You can't use Optinal types like non-Optional types. It is necessary unwrapping the value of an Optional instance before using it in many context. Swift provides several ways to safely unwrap optinal values.
example)
let imagePaths = ["star": "/glyphs/star.png",
"portrait": "/images/content/portrait.jpg",
"spacer": "/images/shared/spacer.gif"]
Getting a dictionary's value using a key returns an optinal value. So
imagePaths["start"] has type Optinal<String> orString?
Use postfix optinal chaining operator (postfix ?).
if imagePath["start"]?.hasSuffix(".png") == true{
print("The star image is in PNG format")
}
this example uses optinal chaining to access the hasSuffix(_:) method on String? instance .
Using the nil-coalescing operator (??) to supply a default value in case the Optinal instance is nill. The ?? operator also work with another Optinal instance on the right-hand side. It can be chained together.
let shapePath = imagePaths["cir"] ?? imagePaths["squ"]?? defaultImagePath
print(shapePath)
// Prints "/images/default.png"
When an instance of Optional is certain that contains a value, you can unconditionally unwrap the value by using the forced unwrap operator(postfix ! ). Unconditinal unwrapping a nil instance with ! triggers a runtime error
let number = Int("42")!
print(number)
//prints "42"
this also can be performed optinal chaining by using the postifx ! operator
let isPNG = imagePaths["star"]!.hasSuffix(".png")
print(isPNG)
// Prints "true"
Optional binding works within a conditional if-let statement. You assign the optional to a temporary constant of corresponding non-optional type. if your optinal has a value then the statement is valid and you proceed using non-optinal constant. if not, you can handle the case with an else clause.
if let r1 = reading1,
let r2 = reading2,
let r3 = reading3 {
let avgReading = (r1 + r2 + r3) / 3
} else {
let errorString = "Instrument reported a reading that was nil."
}
참조
애플 개발자 문서
IOS programming