• Home
  • MAD
    • IOS Series
    • Android Series
    • Flutter Series
    • Xamarin Series
  • Concept Series
    • Software Design
    • Software Arch
    • GIT & Github
    • System Design
    • Cloud
    • Database Integration
    • Push Notification
    • API Integration
    • Cocoa PODS
  • DSA
  • Interview
  • Tips&Tricks
  • YT
  • Home
  • MAD
    • IOS Series
    • Android Series
    • Flutter Series
    • Xamarin Series
  • Concept Series
    • Software Design
    • Software Arch
    • GIT & Github
    • System Design
    • Cloud
    • Database Integration
    • Push Notification
    • API Integration
    • Cocoa PODS
  • DSA
  • Interview
  • Tips&Tricks
  • YT
  • #News
  • #APPS
  • #Events
    • #WWDC
    • #I/O
    • #Ignite
  • #Let’s Talk

MyCodeTips mycodetips-newlogocopy1

  • Home
  • MAD
    • IOS Series
    • Android Series
    • Flutter Series
    • Xamarin Series
  • Concept Series
    • Software Design
    • Software Arch
    • GIT & Github
    • System Design
    • Cloud
    • Database Integration
    • Push Notification
    • API Integration
    • Cocoa PODS
  • DSA
  • Interview
  • Tips&Tricks
  • YT
Swift

Optional in Swift !

An optional in Swift is basically a constant or variable that can hold a value OR no value. The value can or cannot be nil. It is denoted by appending a “?” after the type declaration.

An optional in Swift is basically a constant or variable that can hold a value OR no value. The value can or cannot be nil. It is denoted by appending a “?” after the type declaration.

Optional : A type that represents either a wrapped value or nil, the absence of a value.

Declaration : @frozen enum Optional<Wrapped>

Optional Binding

To conditionally bind the wrapped value of an Optional instance to a new variable, use one of the optional binding control structures, including if let, guard let, and switch.

if let starPath = imagePaths["star"] {
    print("The star image is at '\(starPath)'")
} else {
    print("Couldn't find the star image")
}
// Prints "The star image is at '/glyphs/star.png'"

optional Integer declaration − var perhapsInt: Int?

optional String declaration − var perhapsStr: String?

Optional Chaining

To safely access the properties and methods of a wrapped instance, use the postfix optional chaining operator (postfix ?). The following example uses optional chaining to access the hasSuffix(_:) method on a String? instance.

if imagePaths["star"]?.hasSuffix(".png") == true {
    print("The star image is in PNG format")
}
// Prints "The star image is in PNG format"

Using the Nil-Coalescing Operator

Use the nil-coalescing operator (??) to supply a default value in case the Optional instance is nil. Here a default path is supplied for an image that is missing from imagePaths.

let defaultImagePath = "/images/default.png"
let heartPath = imagePaths["heart"] ?? defaultImagePath
print(heartPath)
// Prints "/images/default.png"
The ?? operator also works with another Optional instance on the right-hand side. As a result, you can chain multiple ?? operators together.

let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
print(shapePath)
// Prints "/images/default.png"

Unconditional Unwrapping

When you’re certain that an instance of Optional contains a value, you can unconditionally unwrap the value by using the forced unwrap operator (postfix !). For example, the result of the failable Int initializer is unconditionally unwrapped in the example below.

let number = Int("42")!
print(number)
// Prints "42"
You can also perform unconditional optional chaining by using the postfix ! operator.

let isPNG = imagePaths["star"]!.hasSuffix(".png")
print(isPNG)
// Prints "true"
Unconditionally unwrapping a nil instance with ! triggers a runtime error.

Forced Unwrapping

If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. This just means putting an exclamation mark at the end of the variable.
var myString:String?

myString = "Hello, Swift 4!"

if myString != nil {
   print(myString)
} else {
   print("myString has nil value")
}

Automatic Unwrapping

You can declare optional variables using exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value.

var myString:String!
myString = "Hello, Swift 4!"

if myString != nil {
   print(myString)
} else {
   print("myString has nil value")
}

Creating an Optional Value

case some(Wrapped) : The presence of a value, stored as Wrapped.
init(Wrapped) 	   : Creates an instance that stores the given value.

Creating a Nil Value

case none : The absence of a value.
init(nilLiteral: ()) : Creates an instance initialized with nil.

Transforming an Optional Value

func map<U>((Wrapped) -> U) -> U? : Evaluates the given closure when this Optional instance is not nil, passing the unwrapped value as a parameter.

func flatMap<U>((Wrapped) -> U?) -> U? : Evaluates the given closure when this Optional instance is not nil, passing the unwrapped value as a parameter.

Coalescing Nil Values

func ?? <T>(T?, () -> T) -> T : Performs a nil-coalescing operation, returning the wrapped value of an Optional instance or a default value.

func ?? <T>(T?, () -> T?) -> T? : Performs a nil-coalescing operation, returning the wrapped value of an Optional instance or a default Optional value.

Comparing Optional Values

static func == (Wrapped?, Wrapped?) -> Bool : Returns a Boolean value indicating whether two optional instances are equal.

static func != (Optional<Wrapped>, Optional<Wrapped>) -> Bool : Returns a Boolean value indicating whether two values are not equal.

Encoding and Decoding

func encode(to: Encoder) : Encodes this optional value into the given encoder.
init(from: Decoder) : Creates a new instance by decoding from the given decoder.

Publishing an Optional

var publisher: Optional<Wrapped>.Publisher : A Combine publisher that publishes this instance’s value to each subscriber exactly once, if it has a value at all.

struct Optional.Publisher : The type of a Combine publisher that publishes the value of a Swift optional instance to each subscriber exactly once, if the instance has any value at all.

Type Aliases

typealias Optional.Body
typealias Optional.DecodingConfiguration
typealias Optional.EncodingConfiguration
typealias Optional.Value

-Initializers : init(from: Decoder, configuration: Wrapped.DecodingConfiguration)

-Instance Methods : func encode(to: Encoder, configuration: Wrapped.EncodingConfiguration)

Happy Swift Coding 🙂

Liked it? Take a second to support Ranjan on Patreon!
become a patron button
  • Click to share on Reddit (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • More
  • Click to share on Pocket (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
Written by Ranjan - 4624 Views
Tags | Interview Questions, IOS, swift
AUTHOR
Ranjan

Namaste, My name is Ranjan, I am a graduate from NIT Rourkela. This website is basically about of what i learnt from my years of experience as a software engineer on software development specifically on mobile application development, design patterns/architectures, its changing scenarios, security, troubleshooting, tools, tips&tricks and many more.

You Might Also Like

ios-15

Whats New in the iOS 15 ?

June 9, 2021
placeholder

How to insert Placeholder in UITextView

March 24, 2020
swift-functions

Swift Functions!

October 13, 2021
Next Post
Previous Post

Support us

mycodetips
mycodetips

Follow us @ LinkedIn 2850+

Subscribe for updates

Join 8,213 other subscribers

Latest Posts

  • YT-Featured-solidprinciples
    SOLID Principles of Software Design
  • IOS 16 Features
    Latest features in IOS 16
  • r-language
    How can R language be used for data analysis?
  • wordpress-coding-blog
    Guide To WordPress Coding Standards
  • YT-Featured-Algorithm
    What is Algorithm?
  • Frameworks of IOS
    Frameworks of IOS – Part ( I )
  • NSFileManager or NSPathUtilities
    NSFileManager or NSPathUtilities in Objective-C
  • Passing data between view controllers in Objective-C
    Passing data between view controllers in Objective-C
  • structures-classes-enum
    Structures and Classes in swift !
  • control-system-swift
    Control Flow in Swift
whiteboard

Whiteboard(PRO)

whiteboard

Whiteboard(lite)

alphabets

Kids Alphabet

techlynk

Techlynk

techbyte

Do2Day

techbyte

Techbyte

  • #about
  • #myapps
  • #contact
  • #privacy
  • #Advertise
  • #myQuestions

Android Android Studio API APP Programming Apps blogging CSS DATABASE dsa Features HTML HTML5 installation Interview Questions IOS iPhone javascript Mac objective-c OS Programming quicktips SDK SEO SQL swift Tips & Tricks Tools UI Web Wordpress Xcode

  • SOLID Principles of Software Design
  • Latest features in IOS 16
  • How can R language be used for data analysis?
  • Guide To WordPress Coding Standards
  • What is Algorithm?

©mycodetips.com