Elye
Elye

Reputation: 60141

Type checking casting of Struct and Class comparison

In Class vs Struct documentation https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html, one of the differences between Struct and Class is

Type casting enables you to check and interpret the type of a class instance at runtime.

I'm trying to understand what that means. Can't really figure out even by looking at https://docs.swift.org/swift-book/LanguageGuide/TypeCasting.html

I tried the following codes

protocol Aprotocol { }

struct Bstruct: Aprotocol {
    func bDoThis() {
        print("B do this")
    }
}

class Cclass: Aprotocol {
    func cDoThis() {
        print("C do this")
    }
}

func dothing(a: Aprotocol) {
    
    switch a {
    case is Bstruct:
        print("this is B")
        (a as? Bstruct)?.bDoThis()
    case is Cclass:
        print("this is C")
        (a as? Cclass)?.cDoThis()
    default:
        print("this is not B")
    }
}

dothing(a: Bstruct())
dothing(a: Cclass())

The is and as works for both Bstruct and Cclass. to me, that's Type Checking and Type Casting, which seems to work for both Struct and Class. Did I miss anything? What's the exact meaning of "Type casting enables you to check and interpret the type of a class instance at runtime." ?

Upvotes: 1

Views: 209

Answers (1)

matt
matt

Reputation: 535305

Consider:

let v : UIView = UIButton()
(v as? UIButton)?.setTitle("howdy", for: .normal)

That works because UIView is a superclass (and UIButton is one of its subclasses). You cannot do that with a struct, because a struct can never be a "superstruct"; there is no inheritance hierarchy among structs.

Your code, on the other hand, is about protocol and adopter, which is a totally different thing. None of your code downcasts a struct or a class; what you do is downcast a protocol, and of course you can downcast it to any adopter, be it class, struct, or enum. But as I say, that is not what that passage in the book is about.

Upvotes: 3

Related Questions