【问题标题】:How to create a datatype with limited set of possibilities to switch on its value?如何创建具有有限可能性的数据类型来打开其值?
【发布时间】:2019-05-10 05:55:35
【问题描述】:

我想将一个值传递给一个函数,让我从集合列表中选择要设置的值。使用此功能的一个示例是需要根据页面所处的“模式”做出不同行为的功能,例如创建新帖子或编辑现有帖子。我目前正在通过将字符串参数传递到字符串中带有“new”或“edit”的函数来执行此操作。我认为正确的方法是创建一个枚举,以便传递的值是该枚举类型,我不必担心拼写错误会破坏应用程序。

我以为我只需要声明一个带有我的选项的枚举作为案例,然后就可以像使用客户数据类型一样使用它。这对我不起作用,要么我犯了一个愚蠢的错误,要么这不是应该的使用方式。

// -------------
// Current Code
func filterBySwitch(filterOption: String){
    print("You asked me to filter by \(filterOption)")
}
filterBySwitch(filterOption: "userOwns")

// -------------
// I though this is how I would pass the argument when only 3 available options
enum filterType {
    case userHeart
    case userOwns
    case userSeen
}
func filterBySwitch(filterOption: filterType){
    print("You asked me to filter by \(filterType)")
}
filterBySwitch(filterOption: .userOwns)

【问题讨论】:

  • 第二组代码在什么方面不适合您?要具体(在您的问题中,不要在评论中回复)。
  • 你说的“那行不通”是什么意思?
  • 所以你想让你的filterBySwitch基于filterType做不同的任务?使用枚举到底对您不起作用的是什么?顺便说一句,你声明枚举大写,就像你声明你的类一样。
  • 您的意思是说print("You asked me to filter by \(filterOption)")?你写了filterType

标签: swift struct enums


【解决方案1】:

你可能想做这样的事情:

enum FilterType {
    case userHeart
    case userOwns
    case userSeen
}
func filterBySwitch(filterOption: FilterType){
    print("You asked me to filter by \(filterOption)") //<-
}
filterBySwitch(filterOption: .userOwns)

在 Swift 中,您使用大写的标识符作为类型,这样的约定将帮助您更容易地发现此类错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多