Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

ios - Calling instance method during initialization in 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()
  }     
}

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:

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

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

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?

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()
} 

Any comment is appreciated. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

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)
  }     
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...