当我必须在 Swift 中的类、结构和枚举之间进行选择时,我应该如何推理? [英] How should I reason when I have to choose between a class, struct and enum in Swift?

查看:24
本文介绍了当我必须在 Swift 中的类、结构和枚举之间进行选择时,我应该如何推理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然类、结构体和枚举都有构造函数、属性和计算属性,我应该如何在它们之间进行选择?

Since classes, structs and enums all has constructors, properties and computed properties, how should I reason when choosing between them?

推荐答案

ChristopheD 和 Jack Wu 的回答很好,但我觉得他们没有触及枚举,或者忽略了它们的重要性.Swift 枚举是(旨在)代数数据类型的完整实现.类和结构传统上用于在面向对象的语言中对数据进行建模,但枚举通常仅限于用作将变量的值限制为有限数量的可能性的便捷方式.例如.(C++):

ChristopheD's and Jack Wu's answers are good, but I feel they don't touch on enums, or miss their importance. Swift enums are (meant to be) a full implementation of algebraic data types. Classes and structs are traditionally used to model data in object-oriented languages, but enums are usually limited to being used as a convenient way to limit the value of a variable to a limited number of possibilities. E.g. (C++):

enum MaritalStatus { Unmarried, Married, Divorced, WidowedOrWidowered };
MaritalStatus m = Unmarried;

Swift 枚举可以完成上述操作,但它们还可以做得更多.当然语言指南有一个很好的条码建模示例 但我所知道的最好的例子是 Scott Wlaschin 的演讲:http://www.slideshare.net/ScottWlaschin/ddd-with-fsharptypesystemlondonndc2013

Swift enums can do the above but they can do a lot more. Of course the Language Guide has a pretty good barcode modelling example but the best example I know of that really drives home the point of modelling data with algebraic data types is Scott Wlaschin's presentation: http://www.slideshare.net/ScottWlaschin/ddd-with-fsharptypesystemlondonndc2013

您可能会从整个演示文稿中受益,但要真正理解"这一点,您需要查看的只是幻灯片 60,他展示了如何在典型的业务线应用中为付款方式"建模.

You would probably benefit from going through the whole presentation but really to 'get' the point all you need to see is slide 60 where he shows how to model a 'payment method' in a typical line-of-business app.

演示文稿中的示例使用 F#,但 F# 与 Swift 相去甚远,您可以很容易地在它们之间进行映射.例如,Swift 中的支付方式枚举如下所示:

The examples in the presentation are in F# but F# isn't that far off from Swift and you can pretty easily map between them. E.g., the payment methods enum in Swift would look like:

enum PaymentMethod {
    case cash // No extra data needed.
    case cheque(Int) // Cheque #.
    case card(CardType, CardNumber) // 2 pieces of extra data.
}

上面的重点是每个订单的支付方式只能是上述三种方式中的一种.编译器将不允许任何其他内容.这是构建整个类层次结构以对这些几乎微不足道的事物建模的非常简洁的替代方法.

The point of the above is that each order's payment method can be only one of the above three methods. Anything else will not be allowed by the compiler. This is a very succinct alternative to building entire class hierarchies to model these almost trivial things.

演示真正从那里开始,最好的部分是 Swift 几乎可以完成 F# 在数据建模、使用可选类型等方面的所有功能.

The presentation really takes off from there and the best part is Swift can do almost everything that F# can in terms of data modelling, using optional types, etc.

这篇关于当我必须在 Swift 中的类、结构和枚举之间进行选择时,我应该如何推理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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