由于 SwiftUI 及其将方法分解为括号的能力(感谢函数生成器),如下所示:
struct ContentView : View {
var body: some View {
VStack {
Text("Hello World!")
Text("by Purple Giraffe").color(.gray)
}
}
函数构建器代码只是为了强调分解可以很方便的事实。我不希望它帮助我进行分解分配。
我想知道是否可以将分配(带有其他东西)分解成括号,如下所示:
struct AnimationViewConfiguration {
var contentMode:Int = 0
var mainTitle:String = "test"
var subTitle:String = ""
var alternativeSubtitle:String = ""
var numberOfIteration:Int = 0
var frameRate = 40
var maximumSimultaneousParalax:Int = 5
var minimumSimultaneousParalax:Int = 2
}
class someViewController: UIViewController {
var mainBackgroundAnimationViewConfig = AnimationViewConfiguration()
func animateBackground(_ useAlternativeBackground:Bool) {
// The normal bulky way
if useAlternativeBackground == false {
mainBackgroundAnimationViewConfig.contentMode = 3
mainBackgroundAnimationViewConfig.mainTitle = "Your super animation"
mainBackgroundAnimationViewConfig.subTitle = "A subtitle anyway"
mainBackgroundAnimationViewConfig.alternativeSubtitle = "Hey another one!"
// partial or complete assignation
// mainBackgroundAnimationViewConfig.numberOfIteration = 4
mainBackgroundAnimationViewConfig.frameRate = 40
mainBackgroundAnimationViewConfig.maximumSimultaneousParalax = 19
mainBackgroundAnimationViewConfig.minimumSimultaneousParalax = 3
} else {
// The way I'd like it to be
mainBackgroundAnimationViewConfig with { // imaginary `with` keyword
contentMode = 0
mainTitle = "Your super animation"
subTitle = "A subtitle anyway"
alternativeSubtitle = "Hey another one!"
// partial or complete assignation
// numberOfIteration = 4
frameRate = 40
maximumSimultaneousParalax = 19
minimumSimultaneousParalax = 3
}
}
}
}
关键是要避免重复长变量名 15 次,因为您知道您经常使用 2,3,4 缩进来执行此操作(这使得抓住眼睛更加烦人)。
对于建议将其放在特定函数中的人,我想说出于同样的原因,我们有时会使用匿名函数(即只使用一次......),在不制作更多样板的情况下进行分配仍然很方便。
感谢@matt 提到with
其他语言中用于此目的的关键字~
如果它不存在,它会在 swift5.1+ 中出现吗?
你不觉得它很方便吗?