在Swift初始化期间调用实例方法

编程入门 行业动态 更新时间:2024-10-24 11:17:44
本文介绍了在Swift初始化期间调用实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我刚开始使用Swift,并且想要使用如下的实例方法初始化对象的成员变量:

I am new to Swift and would like to initialize an object's member variable using an instance method like this:

class MyClass { var x: String var y: String func createY() -> String { self.y = self.x + "_test" // this computation could be much more complex } init(x: String) { self.x = x self.y = self.createY() } }

基本上,不是内联 init 方法中的所有初始化代码,我想提取 y 到专用方法 createY 并在 init中调用此实例方法 createY 。但是,Swift编译器(Xcode 6.3测试版中的Swift 1.2编译器)抱怨:

Basically, instead of inlining all the initialization code in init method, I want to extract the initialization code of y to a dedicated method createY and call this instance method createY in init. However, Swift compiler (Swift 1.2 compiler in Xcode 6.3 beta) complains:

在超级.init initialize self

use of 'self' in method call 'xxx' before super.init initialize self

这里的'xxx'是实例方法的名称(createY)。

Here 'xxx' is the name of the instance method (createY).

我可以理解Swift编译器的抱怨和潜在的问题。但是,我不知道如何解决它。 Swift中正确的方法应该是在 init ?

I can understand what Swift compiler is complaining and the potential problem it wants to address. However, I have no idea how to fix it. What should be the correct way in Swift to call other instance method of initialization code in init?

中调用初始化代码的其他实例方法。使用以下技巧作为工作,但我不认为这是这个问题的惯用解决方案(和这个解决方法要求使用声明 y var 而不是 let 这也让我感到不安):

Currently, I use the following trick as work around but I don't think this is the idiomatic solution to this problem (and this workaround requires y to be declared using var instead of let which makes me feel uneasy too):

init(x: String) { self.x = x super.init() self.y = createY() }

感谢任何评论。感谢。

推荐答案

将 createY()转换为全局或类函数接受 x 作为参数,并返回 y 。

Convert createY() to a global or class function that accepts x as an argument and returns a y.

func createY(x: String) -> String { return x + "_test" // this computation could be much more complex }

然后,通常从 init 中调用它。

Then just call it normally from your init.

class MyClass { let x: String let y: String init(x: String) { self.x = x self.y = createY(x) } }

更多推荐

在Swift初始化期间调用实例方法

本文发布于:2023-11-28 07:41:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   实例   方法   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!