Swift-如何使用函数或其他模式初始化struct实例

时间:2018-02-23 05:29:51

标签: swift function design-patterns struct

这是一个愚蠢的例子,但是当我尝试初始化下面的struct实例时,我无法想到避免重复自己的正确方法。注意他们如何获得相同的初始化器(不确定这是否是正确的短语),但是另一种方法是这样做,因此我给它一个函数或类似的东西而不是相同的结构。的init()?

struct InnerSt {
    var a: String
    var b: String
}

var myStructs: [InnerSt] = []

func assignVal() {
    for item in ["dog", "cat", "fish"] {
        let a: String = "I'm a"
        var pets: String
        let inner: InnerSt = InnerSt.init(a: a, b: item)
        switch item {
        case "dog":
            pets = "hairy"
            //print(inner.a + " " + inner.b + " and I'm " + pets)  //this is like what I want to repeatedly do without the repetition
            myStructs.append(inner) //this works nicely but obviously I miss adding the pets variable
        case "cat":
            pets = "furry"
            //print(inner.a + " " + inner.b + " and I'm " + pets)
            myStructs.append(inner)
        case "fish":
            pets = "scaly"
            //print(inner.a + " " + inner.b + " and I'm " + pets)
            myStructs.append(inner)
        default: ()
        }
    }
}

assignVal()
print(myStructs)

1 个答案:

答案 0 :(得分:0)

为避免编写大量初始化工具,您只需按以下步骤更改实现:

func assignVal() {
    let a = "I'm a "
    for item in [1, 2] {
        let temp = InnerSt.init(a: a, b: item)
        print(temp)
    }
}

基本上,您不需要switch,因为循环时会分配item。它将在第一次迭代时分配1的值,在第二次迭代时分配2

好处是:

  1. InnerSt初始化程序只写一次(即使它被多次调用)。
  2. 如果您的数组[1, 2]增长(说[1, 2, 3]),则无需向case添加新的switch
  3. 在开始时帮助我的一些旁注:

    • InnerSt.init(a: a, b: item)可缩短为InnerSt(a: a, b: item)。很好的可读性。
    • let a: String = "I'm a"可以缩短为let a = "I'm a"。 Swift有一个很好的类型推理系统。在这种情况下,编译器会推断a的类型为String
    • innserSt会更好地命名为InnerSt。见Apple's excellent guidelines

    评论后的修订

    游乐场代码:

    var petsDescriptions: [String] = [] // array of string descriptions of the animals
    var pets = ["dog", "cat", "fish", "deer"] // array of all animals
    
    func assignVal() {
    
        for pet in pets {
    
            var surfaceFeeling: String = "" // variable to hold the surface feeling of the pet e.g. "hairy"
    
            switch pet { // switch on the pet
            case "dog":
                surfaceFeeling = "hairy"
            case "cat":
                surfaceFeeling = "furry"
            case "fish":
                surfaceFeeling = "scaly"
            default:
                surfaceFeeling = "<unknown>"
            }
    
            let description = "I'm \(surfaceFeeling) and I'm a \(pet)" // construct the string description
            petsDescriptions.append(description) // add it to the storage array
        }
    }
    
    assignVal()
    print(petsDescriptions)
    

    控制台输出:

    ["I\'m hairy and I\'m a dog", "I\'m furry and I\'m a cat", "I\'m scaly and I\'m a fish", "I\'m <unknown> and I\'m a deer"]
    

    如果我正确回答了您的问题或需要添加更多信息,请告诉我。