Intro to iOS Development
  • Welcome
    • β˜€οΈIntroduction
    • 🐣Getting Started
    • 🐦Course Staff
  • Logistics
    • πŸ“œSyllabus
    • πŸ—“οΈSchedule
    • πŸ–ŠοΈGrading
    • πŸ™‹β€β™‚οΈOffice Hours
    • Ed Discussion
  • Assignments
    • 🍼A1: Swift Basics
    • πŸ§‘A2: Profile
    • πŸ’¬A3: ChatDev
    • πŸ‘¨β€πŸ³A4: ChefOS
    • πŸ‘¨β€πŸ³A4: ChefOS - SwiftUI
    • πŸ“±Hack Challenge
      • πŸ†FA23 Winners
  • Lectures
    • 1️⃣Logistics + Swift Basics
    • 2️⃣UIKit + AutoLayout
  • 3️⃣MVC + Navigation + Delegation
  • 4️⃣UITableView
  • 5️⃣UICollectionView
  • 6️⃣Networking I
  • 7️⃣Networking II
  • 8️⃣SwiftUI I
  • 9️⃣SwiftUI II
  • πŸ”ŸPersistence + SnapKit
  • πŸ””(11) Notifications
  • 🌎(12) Deployment and MapKit
  • Chapters
    • πŸ–οΈIntroduction
    • ☁️Git + GitHub
      • 1️⃣Git Installation
      • 2️⃣Git Basics
      • βž•Git+
    • 🐣Swift Basics
      • 1️⃣Variables and Constants
      • 2️⃣Data Types
      • 3️⃣Operators
      • 4️⃣Data Structures
      • 5️⃣Conditionals
      • 6️⃣Loops
      • 7️⃣Functions
      • 8️⃣Closures
      • 9️⃣Optionals
    • 🧰UIKit + AutoLayout
      • 1️⃣Classes
      • 2️⃣UIKit
      • 3️⃣AutoLayout
    • πŸ“ΊMVC + Navigation + Delegation
      • 1️⃣MVC
      • 2️⃣Navigation
      • 3️⃣Delegation
    • πŸ“UITableView
      • 1️⃣What is a UITableView?
      • 2️⃣UITableView Setup
    • πŸ“šUICollectionView
      • 1️⃣What is a UICollectionView?
      • 2️⃣UICollectionView Setup
    • 🌐Networking I
      • 1️⃣HTTP Requests
      • 2️⃣Callbacks
      • 3️⃣Codable
    • 🌍Networking II
      • 1️⃣Alamofire
      • 2️⃣GET Requests
      • 3️⃣POST Requests
      • 4️⃣URLSession
    • πŸ’ΎPersistence + SnapKit
      • 1️⃣Persistence
      • 2️⃣SnapKit
    • πŸ•ŠοΈSwiftUI
      • 1️⃣Introduction to SwiftUI
      • 2️⃣Getting Started with SwiftUI
      • 3️⃣Views + Modifiers
      • 4️⃣Layouts
      • 5️⃣Navigation
      • 6️⃣Property Wrappers
    • πŸŽ›οΈWidgets
      • 1️⃣Introduction to Widgets
      • 2️⃣Setting Up Widgets
      • 3️⃣Building Widgets
      • 4️⃣Configuring Widgets
    • 🧱Project Foundation
    • βœ…Testing
      • 1️⃣Unit Testing
    • πŸ‘£Debugging
      • 1️⃣OSLog
      • 2️⃣Crashlytics
      • 3️⃣Analytics
    • ☁️CI/CD
      • 1️⃣Xcode Cloud
      • 2️⃣AppStore Shipping
  • Guides
    • πŸ”¨Xcode Project Setup
    • 🎨Figma
    • πŸ“¬Postman
    • πŸ₯₯CocoaPods
    • 🧰UIKit Handbook
    • πŸ“‘Tab Views
      • UITabBarController
      • TabView
  • Work in progress
    • 🧡Concurrency
    • 2️⃣UI Testing
    • πŸ•Reactive Programming
    • 🧠Memory Management
      • πŸ”ARC
    • πŸ“¦Storage
    • πŸ“£Notifications
  • Archived
    • SP24
      • Logistics
        • πŸ“œSyllabus
        • πŸ—“οΈSchedule
        • πŸ–ŠοΈGrading
        • πŸ™‹β€β™‚οΈOffice Hours
      • Assignments
        • 🍼A1: Swift Basics
        • πŸ§‘A2: Profile
        • πŸ’¬A3: ChatDev
        • πŸ‘¨β€πŸ³A4: ChefOS
        • πŸ“±Hack Challenge
          • πŸ†FA23 Winners
      • Lecture
        • 0️⃣Course Intro + Logistics + Git Setup
        • 1️⃣Swift Basics
        • 2️⃣UIKit + AutoLayout
        • 3️⃣MVC + Navigation + Delegation
        • 4️⃣UITableView
        • 5️⃣UICollectionView
        • 6️⃣Networking I
        • 7️⃣Networking II
        • 8️⃣Persistence + SnapKit
        • πŸ”ŸSwiftUI
        • πŸ”’TabViews
    • FA23
      • Logistics
        • 🐣Getting Started
        • 🐦Course Staff
        • πŸ“œSyllabus
        • πŸ—“οΈSchedule
        • πŸ–ŠοΈGrading
        • πŸ™‹β€β™‚οΈOffice Hours
      • Assignments
        • 🍼A1: Swift Basics
        • πŸ§‘A2: Profile
        • πŸ’¬A3: ChatDev
        • πŸ‘¨β€πŸ³A4: ChefOS
        • πŸ“±Hack Challenge
          • πŸ†FA23 Winners
      • Lectures
        • 0️⃣Course Intro + Logistics
        • 1️⃣Swift Basics
        • 2️⃣UIKit + AutoLayout
        • 3️⃣MVC + Navigation + Delegation
        • 4️⃣UITableView
        • 5️⃣UICollectionView
        • 6️⃣Networking I
        • 7️⃣Networking II
        • 8️⃣Persistence + SnapKit
        • πŸŽ›οΈWidgets
          • πŸ‘ΌIntroduction to Widgets
          • βš’οΈSetting Up Widgets
          • 🧱Building Widgets
          • πŸ‘¨β€πŸ’»Configuring Widgets
        • πŸ”ŸSwiftUI
    • SP23
      • Logistics
        • Lecture Schedule
        • Syllabus
        • Grading
        • SP23 Office Hours
      • Chapters
        • 1. Intro to Swift & Xcode
          • Lecture Handout
          • Lecture Demo
          • 🍼Project: Swift Basics
        • 2. UIKit and AutoLayout
          • Lecture Handout
          • Lecture Demo
          • πŸ›’Project: UIKit + AutoLayout
        • 3. Navigation, MVC, and Delegation
          • Lecture Handout
          • Lecture Demo
          • Project: Navigation + Delegation
        • 4. UITableView
          • Lecture Handout
          • Lecture Demo
          • Project: UITableView
        • 5. UICollectionView
          • Lecture Handout
          • Lecture Demo
          • Project: UICollectionView
        • 6. Networking I
          • Lecture Handout
          • Lecture Demo
          • Project: Persistence
        • 7. Networking II
          • Lecture Handout
          • Lecture Demo
            • Message Board
          • Project: Networking II
        • 8. Swift UI
        • 9. CocoaPods
          • 🍫Lecture Handout
          • πŸ§‘β€πŸ³Lecture Demo
      • Cheat Sheets
        • Setting Up a New Xcode Project
        • Submitting Your Projects
        • Setting Up CocoaPods
    • 2022
      • SwiftUI
    • 2021
      • Adding Flare
      • Project: UIView Animations (Optional - Extra Credit)
      • UIView Animations
      • Xcode Tips and Tricks
    • 2019
      • Firebase
      • Persistence: UserDefaults
  • Swift Guide (ARCHIVED)
    • About this Textbook
    • Documentation
    • Constants and Variables
      • Variable Properties
      • Lazy and Static Variables
    • Functions
    • Ranges
    • Arrays
      • Basic Array Operations
      • Iteration and Enumeration
      • Advanced Array Operations
    • Tuples
    • Conditions and While Loops
    • For Loops
    • Enums and Switches
      • Enums with Associated Values
      • Indirect Enums
    • Classes and Structs
    • Optionals
    • Dictionaries
      • Dictionary Implementation
    • Closures
    • Constraints
    • Generics
    • Protocols
      • Protocols With Associated Types
    • Casting
    • Errors
    • Networking
      • Result
    • Inout
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Swift Guide (ARCHIVED)

Casting

There will be times when you want to convert from one type to another. For this, we use a process called "type casting", which uses the keyword as: object as(?/!) type. If object is of type type or is a subtype of type type then there will be a successful casting to type. This also works for protocols if you want to encapsulate features. For types that are guaranteed to be able to convert, we can use the direct as. This works for anything that is already declared to be the casting type:

let x = 3
// x: Int = 3
let y = x as Int

Or for objects that are declared to be subclasses to the casting type or a conformant of the conforming type.

class aClass {}
class aSubClass: aClass {}

let myObject = aSubClass() as aClass
// myObject: aClass = aSubClass()

protocol aProtocol {}
class aConformant: aProtocol {}

let myProtocolConformant = aConformant() as aProtocol
// myProtocolConformant: aProtocol = aConformant()

Casting Down

As you can imagine, this process gets a little more complicated when we can't guarantee successful casting. This happens when we are casting from superclass to subclass or unrelated types. In these cases, the casting will be optional–i.e. if the casting fails, it will return nil. As with every other optional type we have dealt with before, we need to handle the optional. We can either leave it as an optional with as? or we can force unwrap it with as!.

class aClass {}
class aSubClass: aClass {}

let myEncapsulatedObject: aClass = aSubClass()
// myEncapsulatedObject: aClass = aSubClass()
let myObject = myEncapsulatedObject as? aSubClass
// myObject: aSubClass = aSubClass()

let undeclaredType: Any = 3
// undeclaredType: Any = 3
let myInt = undeclaredType as! Int
// myInt: Int = 3

let myFailingCast = undeclaredType as! String
// Could not cast value of type Int to String

Note: When casting to a protocol, if you do not explicitly conform to the protocol in your code, the cast will fail! No duck typing allowed!

PreviousProtocols With Associated TypesNextErrors

Last updated 1 year ago

Was this helpful?