[英]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
。
好處是:
InnerSt
初始化程序只寫入一次(即使多次調用)。 [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具有出色的類型推斷系統。 在這種情況下,編譯器將推斷a
為String
類型。 innserSt
將InnerSt
命名為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.