在Swift中使用枚举与相关值是否违反了Liskov替代原则? [英] Does using enum with associated value in Swift violate Liskov Substitution Principle?

查看:170
本文介绍了在Swift中使用枚举与相关值是否违反了Liskov替代原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

enum WeatherType {
    case cloudy(coverage: Int)
    case sunny
    case windy
}

我刚刚在Swift教程中看到这一点,我不敢相信他们允许你这样做。现在,每当我启用该枚举时,我必须为多个创建一个特殊情况。

I just saw this in a Swift tutorial and I can't believe they allow you to do that. Now, whenever I switch on that enum, I gotta create a special case for cloudy!

推荐答案

你不会做任何事情。如果你不在乎覆盖面是什么,不要问什么是覆盖面。如果你不在乎多云,不要问是否多云。

You don't "gotta" do anything. If you don't care what the coverage is, don't ask what the coverage is. If you don't care if it's cloudy, don't ask if it's cloudy. There is nothing special about the way you write a switch for a case that has an associated value.

假设我们有这样的一个例子:

Suppose we have this:

let weather = WeatherType.cloudy(coverage:1)

然后这是完全合法的:

switch weather {
case .sunny:
    print("it is sunny")
default:
    print("I guess it's cloudy, or maybe windy")
}

同样这样!

switch weather {
case .cloudy:
    print("it is cloudy")
default:
    print("I guess it's sunny, or maybe windy")
}

根本没有任何法律要求你编写一个switch语句。如果您只想知道 weather 是否 .cloudy ,只需要询问:

Nor does any law require you to write a switch statement at all. If you simply want to know whether weather is .cloudy, just ask:

if case .cloudy = weather {
    print("yes it is cloudy")
} else {
    print("I guess it's sunny, or maybe windy")
}

如果你恰好想知道 coverage 是什么,你仍然不必写一个switch语句:

And if you do happen to want to know what the coverage is, you still don't have to write a switch statement:

if case let .cloudy(cov) = weather {
    print("yes it is cloudy, in fact it is \(cov)")
} else {
    print("I guess it's sunny, or maybe windy")
}

你不能做的是 == 。这不会编译:

if weather == .sunny { // error

在这种程度上,是的,具有关联值的枚举与没有关联值的枚举行为不同(如果这是您要求的)。

To that extent, yes, an enum with an associated value behaves differently from an enum without an associated value (if that's what you're asking).

这篇关于在Swift中使用枚举与相关值是否违反了Liskov替代原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆