current position:Home>Technology application of swift phantom type phantom in Apple source code learning

Technology application of swift phantom type phantom in Apple source code learning

2022-05-15 07:37:34Fat knowledge

Practical cases

Phantom A type is just a generic type that is never used inside an object . that , Why does it exist ? Type safety . Let's see how .

In the following example , We have a user 、 Products and a shopping cart . Users and products have the same data type Int64 Of id attribute . Even if they have the same data type , We can also agree that they are two completely different things , There's no comparison at all .

So ? Maybe it's your problem . Find the following code snippet and try to find the error .

struct User {
    let id: Int64
}

struct Product {
    let id: Int64
}

struct ShoppingCart {
    func removeProduct(id: Int64) {
        // removes product with matching id
    }
}

// Create user and a product
let user = User(id: 14)
let laptop = Product(id: 33)

// Create a shopping cart with an initial product
let cart = ShoppingCart(products: [laptop])
// Remove product by id
cart.removeProduct(id: user.id)

You may have noticed , When we try to delete products from the shopping cart , We unexpectedly ended up delivering the user id Not the product id. Because this is a logical error ,Swift Don't know and can't warn us .

But if we can ask Swift Help us in the above situation ? How to follow learning .

ad locum , We created one Id Wrapper object to hold our actual values . It also has a common parameter that is not used inside the object PhantomType . To help you easily create Id object , We meet ExpressiblebyInteger

copyright notice
author[Fat knowledge],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/131/202205102133042936.html

Random recommended