Why use variadic parameters [duplicate] - swift

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am struggling to see if there is an obvious advantage over which method to use when passing values into a function. My code below may not be the best example to explain the decision I'm trying to make, but it is, in my opinion, the easiest to understand.
Variadic Parameter Approach
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for value in numbers {
total += value
}
return total / Double(numbers.count)
}
arithmeticMean(5, 10, 15)
Array Parameter Approach
func arithmeticMean(numbers: [Double]) -> Double {
var total: Double = 0
for value in numbers {
total += value
}
return total / Double(numbers.count)
}
arithmeticMean([5, 10, 15])
Is either of the two techniques preferred? If so, why (speed, reliability or just ease of reading)? Thanks.

I think there is no speed difference.Because,inside the function,you use Variadic Parameter just as Array.
I think that if the parameters count is small,for example,less than 5,Variadic Parameter may be a better solution,because it is easy to read.
If the count of parameters is large. Array is better solution.
Also know that,Variadic Parameter have some limitation:
A function may have at most one variadic parameter, and it must always appear last in the parameter list, to avoid ambiguity when calling the function with multiple parameters.
If your function has one or more parameters with a default value, and also has a variadic parameter, place the variadic parameter after all the defaulted parameters at the very end of the list.
Just from my idea.Hopes helpful

Related

how do i approach "h" parameter to zero in derivative? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a few problem with my derivative because it shows me an error when I approach Denominator to zero .
func derivativeOf(fn: (Double) -> Double, atX x: Double) -> Double {
let h -> 0
return (fn(x + h) - fn(x))/h
}
i know my syntax sucks but currently it is common in calculus and mathematical Differential.
You can't express "number approaching zero" as let h -> 0 - this is just an invalid syntax in Swift.
There's also no specific operator for "number approaching zero". But depending on what you need, you could for example express "smallest possible positive number", using Double.leastNonzeroMagnitude:
let h = Double.leastNonzeroMagnitude

Passing by reference and assigning into a variable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was studying about passing by reference. It made me wonder what would happen in the following example (Written in pseudo-C which supports "by reference"):
int foo(int a) {
a = 5;
return a * 2;
}
int main() {
int a = 1;
a = foo(a);
printf("%d",a);
return 0;
}
What should be printed? if we only did foo(a); without assigning into a then we would get 5. but what would be printed when assigning? should it be 5 or 10?
Since you have a = foo(a); in your main() function, a will contain the result returned by foo(a). foo(a) will always return 10 no matter what a is.
C does not support pass by reference. Changing a = foo(a); to just foo(a); would mean a would retain the value it had before it was passed to foo(), so it would be 1.
One variation of C that supports pass by reference is C++. In C++, you could write foo() as:
int foo(int &a) {
a = 5;
return a * 2;
}
The int &a syntax is used to denote that the parameter will be passed by reference. Now, foo will assign 5 to the referenced variable, but still always return 10.
In this case a = foo(a); will result in a having the value 10, and foo(a); alone will result in a having the value 5.

Modify variable in for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
The code below would print abc 5 times and then print 1024. As far as I understand, in any for, the "iterator " is automatically declared (the equivalent of a C(++)/Java for(int i=1; i<=5; i++) ). Is it possible to actually not automatically create that variable and use the one declared before the for so that it would print abc 5 times and then print 5, thus modifying it?
var i = 1024
for i in 1...5 {
print("abc")
}
print(i)
#DrummerB's answer works, but if you want a for...in loop, this will also work. It's the same principle - declare your variable outside the loop and increment it inside it:
var i:Int = 0
for _ in 0...5 {
print("abc")
i += 1
}
print(i)
Since you aren't referencing a loop variable, Swift syntax recommends an underscore.
You could just rewrite the for loop as a while loop like this:
var i = 1024
i = 1
while i <= 5 {
print("abc")
i = i+1
}
print(i)
If you really want to change the value of the i using the loop in that way, you can do:
var i=1024
for j in 1...5 {
print("abc")
i = j
}
print(i)
The j would be used strictly in the loop, so once finished, it's value is dumped. But a variable declared before (i in your case), could take it's value and maintain it.

Should I always replace if...then...else with a ternary in Swift? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
If I can replace an if...then...else with a ternary, should I do so? Or does it come down to which of the two is the most easy to read and clear?
E.g. change:
If condition {
doSomething
} else {
doSomethingElse
}
to
condition ? doSomething : doSomethingElse
How about with variable assignments :
If condition {
myProperty += 1
} else {
myProperty -= 1
}
to:
myProperty = condition ? myProperty + 1 : myProperty - 1
Edit : Not looking for peoples' opinion on which they prefer, but whether or not there is an accepted professional practice to replace if...then...else with a ternary if possible.
Since both are valid and there is no difference in performance, the goal is readability.
Use a ternary conditional for a simple inline decision.
For anything that wouldn't be appropriate inline or more complicated than basic arithmetic, it would probably be more readable to use normal conditional statements
Apple has a great example of this in the Swift 2.2 docs
Examples from Swift 2.2 Apple docs:
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90
I would say the above is just as readable as below and much cleaner.
let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
rowHeight = contentHeight + 50
} else {
rowHeight = contentHeight + 20
}
// rowHeight is equal to 90
No. The ternary operator should only be used to select the value of one of two expressions. Think of it as being appropriate if your arguments are "nouns". For example:
let wheels = isTricycle ? 3 : 2
In cases that perform actions, or have more complex arguments, use traditional if statements.
Apple says as much in the iBook "The Swift Programming Language", providing only these types of examples of the ternary operator, and specifically stating:
“The ternary conditional operator provides an efficient shorthand for deciding which of two expressions to consider. Use the ternary conditional operator with care, however. Its conciseness can lead to hard-to-read code if overused.”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2 Prerelease).” iBooks.

What are my errors in the following code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is the function:
for (i = 0; i <= array.Length; i++) {
if (array[i].transform.position = 0)
array.RemoveAt(i);
print(“Removed element: “ + array[i].name);
else if (array[i].transform.position > 0)
array[i].transform.forward = Vector3(1,0,0);
}
I'm not sure if this is a valid question but there is for sure some logic errors :
First of all i'm not sure there is a RemoveAt(int index) for arrays
(but i'm not a big unityscript user) (there is for List though)
You should absolutely never (even if some weird languages maybe allow it to you) try to access an object you just deleted... which is what you try to do here :
array.RemoveAt(i);
print(“Removed element: “ + array[i].name);
Position is a Vector3 NOT a int or float so you cannot do : array[i].transform.position = 0
You should never use the = (assignment operator) in an if() you should use the == (comparison operator) (because = returns always true when assignment is possible)
That line is wrong for the same reason as before array[i].transform.position > 0
array[i].transform.forward = Vector3(1,0,0); Leaves me wondering because if it was C# i'd try the new keyword before Vector3() and i'd prefer floats that way :
array[i].transform.forward = new Vector3(1.0F,0,0); But even there Unity will throw you an error stating that you cannot modify components of Transform without making a copy first i believe...
But nice try :D
you can't compare a vector to 0 it needs to be like this
if(myObject.transform.position==Vector3.zero)
and for removing things I'd suggest to include System.Collections.generic lib
then use Listarray then you can use array.RemoveAt(index);