简体   繁体   English

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

[英]Swift- how to initialize struct instance with function or other pattern

This is a dumb example, but I can't think of the right way to avoid repeating myself when I try to initialize my struct instances below. 这是一个愚蠢的示例,但是当我尝试初始化下面的struct实例时,我想不出避免重复自己的正确方法。 Notice how they get the same initializer (not sure if that's the right phrase), but what would be another way to do this so i'm giving it a function or something like that instead of the same struct.init(...)? 请注意,他们如何获得相同的初始化程序(不确定这是否是正确的短语),但是执行此操作的另一种方法是什么,所以我给它提供了一个函数或类似的功能,而不是相同的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)

To avoid writing a bunch of initialisers you could simply change your implementation as follows: 为了避免编写大量的初始化程序,您可以简单地如下更改实现:

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

Basically, you do not need to switch because item is being assigned as you loop. 基本上,您不需要switch因为在循环时已分配了item It will be assigned the value of 1 on the first iteration and 2 on the second. 它将在第一次迭代中分配值为1 ,在第二次迭代中分配值为2

The benefits are: 好处是:

  1. The InnerSt initialiser is written once (even though it is called multiple times). InnerSt初始化程序只写入一次(即使多次调用)。
  2. If your array [1, 2] grows (to say [1, 2, 3] ) you would not need to add new case to your switch . 如果数组[1, 2]增长(比如说[1, 2, 3] ),则无需向switch添加新的case

A few side notes that helped me in the beginning: 最初对我有帮助的一些注意事项:

  • InnerSt.init(a: a, b: item) can be shortened to InnerSt(a: a, b: item) . InnerSt.init(a: a, b: item)可以简化为InnerSt(a: a, b: item) Nice for readability. 可读性好。
  • let a: String = "I'm a" can be shorted to let a = "I'm a" . let a: String = "I'm a"可以将let a: String = "I'm a"简称为let a = "I'm a" Swift has an excellent type inference system. Swift具有出色的类型推断系统。 In this case the complier will infer that a is of type String . 在这种情况下,编译器将推断aString类型。
  • innserSt would be better named InnerSt . innserStInnerSt命名为InnerSt See Apple's excellent guidelines . 请参阅Apple的出色准则

Revision after comments 评论后修订

Playground code: 游乐场代码:

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)

Console output: 控制台输出:

["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"]

Let me know if I answered your question correctly or need to add some more information. 如果我正确回答了您的问题或需要添加更多信息,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM