Variable increment in for loop doesn't work - swift

I have this Swift code:
for var a = 0; a < 10; a++{
println(a)
}
There is an compile error on
a++{
Can anyone explain why?

You just need to add a space between a++ and {:
for var a = 0; a < 10; a++ {
println(a)
}

If you want to use the "{" against your variable you need to use the variable name between the "+" and the "{" as per the swift documentation
for var a = 0; a < 10; ++a{
println(a)
}
Another option as suggest ABakerSmith is to space the operators "+" and "{"
I particularly prefer the first option as it keeps my code consistent as I never use space before my "{" and also it is how is used through all apple documentation

#vacawama and ABakerSmith already told you how to fix it. The reason is that Swift uses whitespace to figure out the difference between multi-character expressions and separate expressions. It requires whitespace between symbols where languages like C don't. It still trips me up sometimes.

Also, for future reference, Swift code allows for two different For loop syntaxes.
for <initialization>; <condition>; <increment> { <statements> }
or when in an array or a collection
for <identifier> in <collection> { <statements> }
But both of them require the attention to detail on where your spaces are in the code, so be careful.
Also, since it seems like you may be rather new at Swift, I recommend checking out these awesome resources that make the journey of learning Swift a lot easier.
Apple's free 500 page Swift Code Reference Guide
Thinkster.io has a great guide for everything swift, even quick little cheat sheets to keep handy for any questions you might have in the future. When I learned swift I used this site a lot!
If you want to build a cool little game using swift start here!
Hope that helped! Swift is a great programming language that has a lot to offer, and I hope you have fun learning it!

Related

Documentation comment for loop variable in Xcode

I know that we can use
/// index variable
var i = 0
as a documentation comment for a single variable.
How can we do the same for a loop variable?
The following does not work:
var array = [0]
/// index variable
for i in array.indices {
// ...
}
or
var array = [0]
for /** index variable */ i in array.indices {
// ...
}
Background:
The reason why I don’t use "good" variable names is that I’m implementing a numerical algorithm which is derived using mathematical notation. It has in this case only single letter variable names. In order to better see the connection between the derivation and the implementation I use the same variable names.
Now I want to comment on the variables in code.
The use of /// is primarily intended for use of documenting the API of of a class, struct, etc. in Swift.
So if used before a class, func, a var/let in a class/struct, etc. you are attaching documentation to that code aspect that Xcode understands how to show inline. It doesn’t know how to pickup that information for things inside of function since at this time that is not the intention of /// (it may work for simple var/let but not likely fully on purpose).
Instead use a simple // code comment for the benefit of any those working in the code however avoid over documenting the code since good code is likely fairly self explaining to anyone versed in the language and adding unneeded documentations can get in the way of just reading the code.
This is a good reference for code documentation in Swift at this time Swift Documentation
I woud strongly push back on something like this if I saw it in a PR. i is a massively well adopted "term of art" for loop indices. Generally, if your variable declaration name needs to be commented, you need a better variable name. There are some exceptions, such as when it stores data with complicated uses/invariants that can't be captured in a better way in a type system.
I think commenting is one area that beginners get wrong, mainly from being misled by teachers or by not yet fully understanding the purpose of comments. Comments don't exist to create an english based, psuedo-programming language in which your entire app will be duplicated. Understanding the programming language is a minimal expectation out of contributors to a project. Absolutely no comments should be explaining programming language features. E.g. var x: Int = 0 // declares a new mutable variable called x, to the Int value 0, with the exception of tutorials for learning Swift.
Commenting in this manner might seem like it's helpful, because you could argue it explains things for beginners. That may be the case, but it's suffocating for all other readers. Imagine if novel had to define all the English words they used.
Instead, the goal of documentation to explain the purpose and the use of things. To answer such questions as:
Why did you implement something this way, and not another way?
What purpose does this method serve?
When will this method of my delegate be called?
Case Study: Equatable
For a good example, take a look at the documentation of Equatable
Some things to notice:
It's written for an audience of Swift developers. It uses many things, which it does not explain such as, arrays, strings, constants, variable declaration, assignment, if statements, method calls (such as Array.contains(_:)), string interpolation, the print function.
It explains the general purpose of this protocol.
It explains how to use this protocol
It explains how you can adopt this protocol for your own use
It documents contractual requirements that cannot be enforced by the type system.
Since equality between instances of Equatable types is an equivalence relation, any of your custom types that conform to Equatable must satisfy three conditions, for any values a, b, and c:
a == a is always true (Reflexivity)
a == b implies b == a (Symmetry)
a == b and b == c implies a == c (Transitivity)
It explains possible misconceptions about the protocol ("Equality is Separate From Identity")

swift programming language

I'm trying to learn a new coding language called swift. But I got a question in mind.
import UIkit
func makeACake (cash:Double, ratio:Double){
print(Making \(cash*ratio)pounds of cake")
}
makeACake(cash:10,ratio:3)
// it will print making 30.0 pounds of cake.
just two questions here.
no.1
why cant i just call makeACake(10,3) why do i have to type it in this manner makeACake(cash:10,ratio:3)
no.2
is the function println removed from swift? why cant i use the function println and it asked me to use print instead.
sorry if i happened to ask any stupid question. but yea just trying to learn coding so maybe help a newbie out? thank you and bless the person who would be kind enough to help me and let me move on.
Every programing language has their own syntax.
Basically, this syntax is acquired from their parent language. The syntax is getting changed in every update.
I have started with swift2 and lot has been changed from swift2 to swift4.
So answering your question,
Answer 1: (_) Underscore --> It is Wildcard pattern
A wildcard pattern matches and ignores any value and consists of an
underscore (_). Use a wildcard pattern when you don’t care about the
values being matched against.
In your example, It means that argument labels are not necessary on invocation of your function.
Learn more about patter at: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Patterns.html
So if you dont want to write parameter name write:
func makeACake ( _ cash:Double, _ ratio:Double){}
Answer 2: print: Introduce First in swift2, we used to type println in swift.
Now you might ask why println was removed, and the answer is simple "It is no longer required".
Let me take a simple example:
println("Hello")
println("World")
output: (One next line is extra in output, don't know how to format it here)
Hello
World
While with print
print("Hello")
print("World")
output: HelloWorld
Later in swift2 println was deprecated and the same("Next Line") output can be achieved with print itself.
"Evolution"
They are making swift "Easy to Learn", "Easy to code" language

Is there any technical benefit in adding semicolons in Swift?

I wrote couple of programs in Objective-C.
I've seen that Swift syntax does not require use of semicolons.
My question is - is there any technical point in using them anyway?
The short answer is: No.
Swift does not require a semicolon after each statement in your code. They are only required if you wish to combine multiple statements on a single line.
Do not write multiple statements on a single line separated with semicolons.
Preferred:
var swift = "not a scripting language"
Not Preferred:
var swift = "not a scripting language";
For more informations, please refer to this page:
https://github.com/raywenderlich/swift-style-guide#semicolons
There are (or used to be) situations where two separate statements on two different lines would taken by the compiler as a single statement. The typical locus is return followed by another statement that you don't want executed. In that situation, and in that situation alone, the semicolon is crucial.
override func viewDidLoad() {
super.viewDidLoad()
return // need semicolon here
print(1) // oops
}
However, in modern Swift the compiler warns and compensates. Adding a semicolon (return;) quiets the warning (though it then causes a different warning).
Otherwise, a semicolon never has any technical benefit.
Yes there is, you can write multiple statements in one line. For example you could write statements more compact when needed, for example:
var progress: Progress {
get { _progress.value }
set { _progress.value = newValue; parent?.update() }
}
Use sparingly though. But in this specific case I prefer it instead of expanding everything to a separate line since its still quite readable and only 2 statements.

Logging syntax for Play Framework 2 in Scala

This is a really silly question, but how can you do convenient formatting of log strings in Play Framework 2 (and in Scala?).
I've googled but its very difficult to find an example, essentially most links are talking about configuring Logback in the first place which I've done fine.
I'm basically trying to find the best stylistic way to do something like:
if(Logger.isDebugEnabled)
Logger.debug("Modified: Id = '" + real_session_id + "', Modified = " + modified.toString)
Coming from a C# background (and log4net) I'd assume you could do something like:
if(Logger.isDebugEnabled)
Logger.debug("Modified: Id = '{0}', Modified = {1}", real_session_id, modified.toString)
But I can't see how this would work with the trait the way it is defined. I've also seen vague references to how you might be able to avoid checking Logger.isDebugEnabled by using a lazy evaluative syntax like:
Logger.debug("Modified: Id = ${real_session_id}, Modified = ${modified.toString}")
That uses Scala macros - but again, that doesn't work and I can find very little information about it.
Am I missing something really blatant here?
The framework used for logging is logback. When you type : Logger.debug, the isDebugEnabled is already implicitly checked.
For the syntax of logging, use the Scala string interpolation.
Logger.debug(s"Modified: Id = '$real_session_id', Modified = $modified.toString")
Why not just use the standard String interpolation capabilities of the language/stdlib? http://docs.scala-lang.org/overviews/core/string-interpolation.html
I apologise if I've missed something crucial about your question.
As to avoiding the if (Logger.isDebugEnabled) check, if the logging framework is not providing some sort of lazy evaluation scheme for arguments passed into it, I would just first consider defining my own wrappers:
object MyLazyLogger {
def debug(msg: => Any) =
if (Logger.isDebugEnabled) Logger.debug(msg)
}
Also, I don't think the way in which you interpolate stuff into the string has anything to do with not evaluating the arguments to debug() if logging is disabled—if debug() declares that it eager-evaluates any arguments passed into it, there's no way that I can see you can change to lazy evaluation at the call site by just using a "special form" of string interpolation. (I'd be happy if anyone proved me wrong here and taught me something new :))
Disclosure: I'm not familiar with Play (yet), so I'm just taking a shot at a general approach here.

Best way to add a "forCount" control structure to Objective-C?

Adam Ko has provided a magnificent solution to this question, thanks Adam Ko.
BTW if, like me, you love the c preprocessor (the thing that handles #defines), you may not be aware there is a handy thing in XCode: right click on the body of one of your open source files, go down near the bottom .. "Preprocess". It actually runs the preprocessor, showing you the overall "real deal" of what is going to be compiled. It's great!
This question is a matter of style and code clarity. Consider it similar to questions about subtle naming issues, or the best choice (more readable, more maintainable) among available idioms.
As a matter of course, one uses loops like this:
for(NSUInteger _i=0; _i<20; ++_i)
{
.. do this 20 times ..
}
To be clear, the effect is to to do something N times. (You are not using the index in the body.)
I want to signal clearly for the reader that this is a count-based loop -- ie, the index is irrelevant and algorithmically we are doing something N times.
Hence I want a clean way to do a body N times, with no imperial entanglements or romantic commitments. You could make a macro like this:
#define forCount(N) for(NSUinteger __neverused=0; __neverused<N; ++__neverused)
and that works. Hence,
forCount(20)
{
.. do this 20 times ..
}
However, conceivably the "hidden" variable used there could cause trouble if it collided with something in the future. (Perhaps if you nested the control structure in question, among other problems.)
To be clear efficiency, etc., is not the issue here. There are already a few different control structures (while, do, etc etc) that are actually of course exactly the same thing, but which exist only as a matter of style and to indicate clearly to the reader the intended algorithmic meaning of the code passage in question. "forCount" is another such needed control structure, because "index-irrelevant" count loops are completely basic in any algorithmic programming.
Does anyone know the really, really, REALLY cool solution to this? The #define mentioned is just not satisfying, and you've thrown in a variable name that inevitably someone will step on.
Thanks!
Later...
A couple of people have asked essentially "But why do it?"
Look at the following two code examples:
for ( spaceship = 3; spaceship < 8; ++spaceship )
{
beginWarpEffectForShip( spaceship )
}
forCount( 25 )
{
addARandomComet
}
Of course the effect is utterly and dramatically different for the reader.
After all, there are alresdy numerous (totally identical) control structures in c, where the only difference is style: that is to say, conveying content to the reader.
We all use "non-index-relative" loops ("do something 5 times") every time we touch a keyboard, it's as natural as pie.
So, the #define is an OKish solution, is there a better way to do it? Cheers
You could use blocks for that. For instance,
void forCount(NSUInteger count, void(^block)()) {
for (NSUInteger i = 0; i < count; i++) block();
}
and it could be used like:
forCount(5, ^{
// Do something in the outer loop
forCount(10, ^{
// Do something in the inner loop
});
});
Be warned that if you need to write to variables declared outside the blocks you need to specify the __block storage qualifier.
A better way is to do this to allow nested forCount structure -
#define $_TOKENPASTE(x,y) x##y
#define $$TOKENPASTE(x,y) $_TOKENPASTE(x, y)
#define $itr $$TOKENPASTE($_itr_,__LINE__)
#define forCount(N) for (NSUInteger $itr=0; $itr<N; ++$itr)
Then you can use it like this
forCount(5)
{
forCount(10)
{
printf("Hello, World!\n");
}
}
Edit:
The problem you suggested in your comment can be fixed easily. Simply change the above macro to become
#define $_TOKENPASTE(x,y) x##y
#define $$TOKENPASTE(x,y) $_TOKENPASTE(x, y)
#define UVAR(var) $$TOKENPASTE(var,__LINE__)
#define forCount(N) for (NSUInteger UVAR($itr)=0, UVAR($max)=(NSUInteger)(N); \
UVAR($itr)<UVAR($max); ++UVAR($itr))
What it does is that it reads the value of the expression you give in the parameter of forCount, and use the value to iterate, that way you avoid multiple evaluations.
On possibility would be to use dispatch_apply():
dispatch_apply(25, myQueue, ^(size_t iterationNumber) {
... do stuff ...
});
Note that this supports both concurrent and synchronous execution, depending on whether myQueue is one of the concurrent queues or a serial queue of your own creation.
To be honest, I think you're over addressing a non-issue.
If want to iterate over an entire collection use the Objective-C 2 style iterators, if you only want to iterate a finite number of times just use a standard for loop - the memory space you loose from an otherwise un-used integer is meaningless.
Wrapping such standard approaches up just feels un-necessary and counter-intuitive.
No, there is no cooler solution (not with Apple's GCC version anyways). The level at which C works requires you to explicitly have counters for every task that require counting, and the language defines no way to create new control structures.
Other compilers/versions of GCC have a __COUNTER__ macro that I suppose could somehow be used with preprocessor pasting to create unique identifiers, but I couldn't figure a way to use it to declare identifiers in a useful way.
What's so unclean about declaring a variable in the for and never using it in its body anyways?
FYI You could combine the below code with a define, or write something for the reader to the effect of:
//Assign an integer variable to 0.
int j = 0;
do{
//do something as many times as specified in the while part
}while(++j < 20);
Why not take the name of the variable in the macro? Something like this:
#define forCount(N, name) for(NSUInteger name; name < N; name++)
Then if you wanted to nest your control structures:
forCount(20, i) {
// Do some work.
forCount(100, j) {
// Do more work.
}
}