为什么我不能调用这个 Swift 计算属性?

问题描述 投票:0回答:1

我创建了一个枚举“Unit”和一个计算属性“description”。当我尝试在 Unit 上使用点注释时,出现错误,提示没有类型。这是因为单位指单位吗? (var unit: Unit) 另外,当我尝试调用描述计算属性时,它说全局变量声明不绑定任何变量。我认为我没有看到这个错误。我是 Swift 的菜鸟,你能帮助我吗? ** 评论的是我遇到错误的地方。

import Foundation

struct Recipe {
    var mainInformation: MainInformation
    var ingredients: [Ingredient]
    var directions: [Direction]
}

struct MainInformation {
    var name: String
    var description: String
    var author: String
    var category: Category
    
    enum Category: String, CaseIterable {
        case breakfast = "Breakfast"
        case lunch = "Lunch"
        case dinner = "Dinner"
        case dessert = "Dessert"
    }
}

struct Ingredient {
    var name: String
    var quantity: Double
    var unit: Unit
    
    
    var description: String {
        let formattedQuantity = String(format: "%g", quantity)
        switch unit{
            case .none:
            let formattedName = quantity == 1 ? name : "\(name)s"
            return "\(formattedQuantity) \(formattedName)"
            default:
            if quantity == 1 {
                return "1 \(unit.singular) \(name)"
            }
            else {
                return "\(formattedQuantity) \(unit.rawValue) \(name)"
            }
            
        }
    }
    
    enum Unit: String, CaseIterable {
        case oz = "Ounces"
        case g = "Grams"
        case cups = "Cups"
        case tbs = "Tablespoons"
        case tsp = "Teaspoons"
        case none = "No units"
        
        var singular: String { String(rawValue.dropLast()) }
    }
    
}

struct Direction {
    var description: String
    var isOptional: Bool
}

var myIngredient = Ingredient(name: "Avocado", quantity: 1.0, unit: .none)

var myIngredientTwo = Ingredient(name: "Avocado", quantity: 1.0, unit: Unit.none)
//Type 'Unit' has no member 'none'

let _ = print(myIngredientTwo.description)


let _ = print(myIngredient.description)
//Global variable declaration does not bind any variables

我尝试使用 Unit.none 来引用枚举 Unit case none 但出现错误。我也尝试了 .none 但当我调用描述计算属性时它也会抛出错误。

swift enumeration computed-properties
1个回答
0
投票

Ingredient
的初始化程序期望
Ingredient.Unit
参数为
unit
类型。

当您传递值

.none
时,编译器可以轻松确定您的意思是
Ingredient.Unit.none
。事实上,如果您愿意,您可以明确地这样做:

var myIngredient = Ingredient(name: "Avocado", quantity: 1.0, unit: Ingredient.Unit.none)

在你的坏例子中,你试图通过

Unit.none
。由于您显式地将
none
范围限定为
Unit
,编译器会尝试查找值为
Unit
none
。由于该行代码位于全局范围内,因此编译器会在顶层查找名为
Unit
的内容。事实证明,Foundation 框架中有一个
Unit
类型定义。并且
Unit
没有名为
none
的成员,因此您的错误。

var myIngredientTwo = Ingredient(name: "Avocado", quantity: 1.0, unit: Unit.none)

那个

Unit
来自基金会,而不是你的
Ingredient
结构。

如果该行代码位于您的

Ingredient
结构体中的某个位置,那么它会起作用,因为编译器会将
Unit
视为嵌套在
Unit
中的
Ingredient

例如:

struct Ingredient {
   ...

   func someFunc() {
       // This works. Compiler can see that Unit is within Ingredient
       var myIngredientTwo = Ingredient(name: "Avocado", quantity: 1.0, unit: Unit.none)
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.