0

I was trying to understand how parameters work in Swift and thus wrote a simple class as follows

class NumberIncreaser { func numberIncrementor(var number:Int)->Int{ number += 1 return number } var anotherNumber = numberIncrementor(3) } 

However even after explicitly mentioning that the method 'numberIncrementor' takes an Int , Xcode asks for a numberIncreaser object(hope I am using the correct terminology , new to programming) instead. I noticed that when I remove the class the method works perfectly fine. I would like to know why this is so and how can I resolve it.

Thanks!

1
  • You problem is in performing code in scope of class. You need to do that in scope of methods or global scope. Commented May 30, 2016 at 14:31

3 Answers 3

0

Also, don't use var in func parameter declarations:

class NumberIncreaser { static func numberIncrementor(number: Int) -> Int { let answer = number + 1 return answer } } var anotherNumber = NumberIncreaser.numberIncrementor(3) 
Sign up to request clarification or add additional context in comments.

Comments

0

var parameters have been deprecated thus number is a constant which makes it immutable. You also cannot call numberIncrementor because it's an instance method.

A way out would be to make numberIncrementor a class or static method by prefixing the declaration with class or static keyword: class func numberIncrementor and you call it like so: NumberIncreaser.numberIncrementor(3).

class NumberIncreaser { class func numberIncrementor(number: Int) -> Int { return number + 1 } var anotherNumber = NumberIncreaser.numberIncrementor(3) } 

Another way would be to make anotherNumber a lazy property like so:

class NumberIncreaser { func numberIncrementor(number: Int) -> Int { return number + 1 } lazy var anotherNumber: Int = self.numberIncrementor(3) } 

Comments

0

Your code won't compile. Consider this:

class NumberIncreaser { static func numberIncrementor(var number:Int)->Int{ number += 1 return number } } var anotherNumber = NumberIncreaser.numberIncrementor(3) 

Or one another variant:

class Number { var number: Int init(number: Int) { self.number = number } func increasedNumber() -> Int { return number + 1 } } var anotherNumber = Number(number: 3).increasedNumber() 

3 Comments

This would definitely work. But, how would you do it if the condition is that another number has to be initialized inside the class?
@AkshanshThakur Consider the second variant. Does it answer to you question?
Wait, i understood. Good job, I'll spend some time on it. Thanks for the response.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.