繁体   English   中英

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

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

这是一个愚蠢的示例,但是当我尝试初始化下面的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)

为了避免编写大量的初始化程序,您可以简单地如下更改实现:

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] ),则无需向switch添加新的case

最初对我有帮助的一些注意事项:

  • InnerSt.init(a: a, b: item)可以简化为InnerSt(a: a, b: item) 可读性好。
  • let a: String = "I'm a"可以将let a: String = "I'm a"简称为let a = "I'm a" Swift具有出色的类型推断系统。 在这种情况下,编译器将推断aString类型。
  • innserStInnerSt命名为InnerSt 请参阅Apple的出色准则

评论后修订

游乐场代码:

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

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

暂无
暂无

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

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