在强制转换的对象中设置值Swift

时间:2019-11-08 15:50:48

标签: swift casting save

我有一个协议.populate('user');,其中包含名称和价格。

结构s正在实现此协议,并且具有另一个名为Food的特定变量。

Fruit(我的ViewController)可以包含每种食物,因此变量color的数据类型为Fridge

第一步,将food变量设置为新的Food

food

然后在我的VC Fruit中,我想使用以下代码修改水果颜色:

fridge.food = Fruit(name: "Apple", price: 0.99, color: "Yellow")

稍后,当我要检索信息时,它会返回“黄色”:

Fridge

现在的问题是,如何正确更改该Castet对象的值?

3 个答案:

答案 0 :(得分:0)

class Fruit{
    var name:String
    var price: Double
    var color:String
    init(name:String,price:Double,color:String) {
        self.name = name
        self.price = price
        self.color = color
    }
}

然后

override func viewDidLoad() {
    super.viewDidLoad()
    let fruit = Fruit(name: "Apple", price: 0.99, color: "Yellow")
    print(fruit.color)// Prints Yellow
    fruit.color = "RED"
    print(fruit.color) //Prints RED
}

答案 1 :(得分:0)

当前代码如下。

protocol Food {
    var name : String {set get}
    var price : Double {set get}
}

struct Fruit : Food {
    var name : String
    var price : Double
    var color : String
}

class Fridge {
    var food : Fruit
    init(food : Fruit) {
       self.food = food
    }
}

class Container {
    var food : Fruit
    init(food : Fruit) {
        self.food = food
    }
}


var container = Container.init(food: Fruit(name: "Apple", price: 0.99, color: "Yellow"))
var fridge = Fridge.init(food:container.food)
var fruit = fridge.food as! Fruit
fruit.color = "Red"
print(fruit.color) // "Red"

var fruit1 = fridge.food as! Fruit
print(fruit1.color) // "Yellow"

因为Fruit是结构类型,而struct是值类型,而不是引用类型

var fruit = fridge.food as! Fruit // it will create a new reference instead of modified the created one.
fruit.color = "Red" 
print(fruit.color) //"Red"

解决方案:

var fridge = Fridge.init(food: container.food)
fridge.food.color = "Red"
print(fridge.food.color) // "Red"

答案 2 :(得分:0)

您始终必须强制转换为as ?,否则在其他类型的情况下会崩溃。

这是正确的方法:

protocol Food {
    var name : String {set get}
    var price : Double {set get}
}

struct Fruit : Food {
    var name : String
    var price : Double
    var color : String
}

class Fridge {
    var food : Food
    init(food : Fruit) {
       self.food = food
    }
}


var fridge = Fridge.init(food: Fruit(name: "Apple", price: 0.99, color: "Yellow"))

print(fridge.food.name) // "Apple"
if let food = fridge.food as? Fruit {
    print(food.color) // "Yellow"
}

if var fruit = fridge.food as? Fruit {
    fruit.color = "Red"
    fridge.food = fruit
}
if let food = fridge.food as? Fruit {
    print(food.color) // "Red"
}