swift programming language - swift

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

Related

Is there an objective reason I can't have a single-element tuple with an element label?

In Swift up to and including Swift 3, I can't create a single-element tuple where the element is named. So func foo() -> Bar is fine whereas func foo() -> (bar: Bar) produces a compiler error.
I can, however, think of a few possible uses for this pattern, e.g.
func putTaskOnQueue() -> (receipt: CancellableTask)
func updateMyThing() -> (updatedSuccessfully: Bool)
...where the label is used to reduce ambiguity as to what the return value represents.
Obviously there are various ways I could re-design my apis to work around this limitation, but I'm curious as to why it exists.
Is this a compiler limitation? Would allowing element labels on 1-tuples break parsing of some other piece of grammar? Has this been discussed as part of the Swift Evolution system?
To be clear: I am not soliciting opinions as to the correctness of the examples above. I'm after explanations (if they exist) as to why this is not technically possible.
Yes, it's due to limitations in the compiler. There are no one-tuples in Swift at all. Every T is trivially convertible to and from (T). SE-110 and SE-111 should improve things, but I'm not sure it will be enough to make this possible and I don't believe any of the current proposals explicitly do make it possible.
It has been discussed on swift-evolution. It's not a desired feature of the language; it's a result of other choices.
The Swift Evolution process is very open. I highly recommend bringing questions like this to the list (after searching the archives; admittedly not as simple as you would like it to be). StackOverflow can only give hearsay; the list is much more definitive.

Swift for in loop with parentheses

I normally use the for in loop in swift without parentheses, but today I put them on just for kicks thinking they were just optional and it did not worked as expected.
This code works:
if let tasks = getAllTasksWithManagedObjectContext(appDelegate.managedObjectContext){
for task in tasks{
appDelegate.managedObjectContext.deleteObject(task)
}
}
This one does not:
if let tasks = getAllTasksWithManagedObjectContext(appDelegate.managedObjectContext){
for (task in tasks){
appDelegate.managedObjectContext.deleteObject(task)
}
}
I get this errors:
Whats going on here?
You are simply not allowed to use parentheses here.
Take a look at the Language Reference -> Statements and compare the C-style for-loop against the swift for-in
for-statement → for­ for-init­;­expression­;­expression­ ­code-block
for-statement → for­ (for-init­;­expression­;­expression­) ­code-block
vs.
for-in-statement → for ­case(opt) ­pattern ­in ­expression ­where-clause­(opt­) code-block
The first one can be used with or without parentheses - your choice as the developer.
However the later one, the one you are actually asking about does not have a version with ( and ), only the one version without them. That means that it is not allowed to use them parentheses around the "argument" of the loop.
Screenshots from the docs linked above for better readability:
vs.

in Swift, what does this specific syntax mean?

I've been attempting to follow some iOS Swift tutorials for connecting to Parse.com
codementor.io tutorial:
loginViewController.fields = .UsernameAndPassword | .LogInButton | .PasswordForgotten | .SignUpButton | .Facebook | .Twitter
makeschool tutorial
loginViewController.fields = [.UsernameAndPassword, .LogInButton, .SignUpButton, .PasswordForgotten, .Facebook]
I assume the former is Switch 1.x, and thelatter is Swift 2. From context they appear to be doing the same thing, but I haven't yet found the language references for the change in syntax. Awfully hard to search for dots, pipes and commas... can someone explain the syntax in each snippet? (I'm working on reading through the language specification, but would be fun to actually get an app to work!)
The old Swift 1 syntax is based on the way you deal with option sets in C and Objective-C: you store an option set in an integer type and use bitwise operators (| and & and ~) to manipulate them. So .UsernameAndPassword | .LogInButton means an option set in which both the .UsernameAndPassword and the .LogInButton options are included. In the old syntax, you use nil to represent an empty option set (in which no options are included), which is not obvious based on the syntax for a non-empty set.
Chris Lattner described the changed syntax in WWDC 2015 Session 106: What's New in Swift. First he describes the problems with the old syntax:
The problem is, when you get to the other syntaxes you end up using, it is a bit less nice. You create an empty-option set with nil -- it doesn't make sense because option sets and optionals are completely different concepts and they're conflated together. You extract them with bitwise operations, which is a pain and super error-prone, and you can get it wrong easily.
Then he describes the new approach:
But Swift 2 solves this. It makes option sets set-like. That means option sets and sets are now formed with square brackets. That means you get empty sets with an empty set of square brackets, and you get the full set of standard set API to work with option sets.
The reason the new syntax works is because OptionSetType conforms to the ArrayLiteralConvertible protocol (indirectly, by conforming to SetAlgebraType). This protocol allows a conforming object to be initialized using an array literal, by having an init that takes a list of elements.
In the new Swift 2 syntax, [ .UsernameAndPassword, .LogInButton ] represents an option set containing both the .UsernameAndPassword and the .LogInButton options. Note that it looks just like the syntax by which you can initialize a plain old Set: let intSet: Set<Int> = [ 17, 45 ]. The new syntax makes it obvious that you specify an empty option set as [].
Swift no longer supports the vertical bar operator used your first line. The second is taking the different cases of an enumeration and describing them as an option set. Here's an example from the Swift docs:
enum CompassPoint {
case North
case South
case East
case West
}
directionToHead = .South
switch directionToHead {
case .North:
print("Lots of planets have a north")
case .South:
print("Watch out for penguins")
case .East:
print("Where the sun rises")
case .West:
print("Where the skies are blue")
}
// prints "Watch out for penguins"

book example not working in SWIFT Playground

I'm looking for an explanation on playground behavior for Swift. On page 76 of the book Beginning Swift Programming the doSomething function doesn't behave in Xcode as described.
func doSomething(num1: Int, num2: Int) {
println(num1, num2)
}
doSomething(5,6)
The book doesn't show an answer, but I expect a response like (5,6). However, I get no error nor any response. Change the action to println(num1) and doSomething(5,6) works. It produces 5. So does doSomething(5). For that matter. Change it to println((num1, num2)) and doSomething(5,6) yields (5,6).
I'm using Xcode v.6.4 on a Mac running Yosemite. What's going on?
As far as I know, the println() function takes only one parameter.
You either do:
println((num1, num2)) // for printing as a Tuple object
or:
println("\(num1), \(num2)") // for printing as a String object
Reference: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309
When in a normal project rather than Playground, the code you provided actually works. However, you will have to call doSomething(5, num2: 6) instead. (Swift 1.2/2.0)
It's Swift basic knowledge and suggest you to look up answer rather than ask here. If you want to print something using println with variable. You have to use \(variableName). For example:
println("\(num1), \(num2)")

Variable increment in for loop doesn't work

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!