book example not working in SWIFT Playground - swift

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

Related

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

Swift: Chaining String/Substring methods yields 'ambiguous use of' errors. Fix or alternative?

I'm trying to do the most basic string manipulation using Swift. It looks like String provides everything I need, even though it relies on Substring intermediate results. So this works
let myString = "0123456789"
let mySubstring = myString.dropFirst(2)
print(mySubstring.dropLast(2))
It successfully yields "234567" as a Substring.
However, when I attempt to chain the calls...
print(myString.dropFirst(2).dropLast(2))
I get the following error...
9> print(myString.dropFirst(2).dropLast(2))
error: repl.swift:9:7: error: ambiguous use of 'dropFirst'
print(myString.dropFirst(2).dropLast(2))
^
Swift.Collection:39:17: note: found this candidate
public func dropFirst(_ n: Int) -> Self.SubSequence
^
Swift.Sequence:20:17: note: found this candidate
public func dropFirst(_ n: Int) -> AnySequence<Self.Element>
^
So it seems like the compiler is understandably having trouble inferring which dropFirst method to invoke because it is defined twice with different return types.
Is there a way around this? Is this just really poor API design on Apple's part? I'm trying to just get a nice easy to read and concise bit of code. I can also make it work by resorting to NSString but this seems wasteful and even more verbose and obtuse.
UPDATE:
I am able to get a better result by adding as Substring after the chain as in...
print(myString.dropFirst(2).dropLast(2) as Substring)
...since that disambiguates the overloaded methods. I would still love to see a more concise solution. Thanks.
If you define the return type, it has no trouble resolving which function to use. There are a number of ways to do this, such as:
let mySubstring: Substring = myString.dropFirst(2).dropLast(2)
Of course, as you say, you can insert this Substring type within the expression:
let mySubstring = (myString.dropFirst(2) as Substring).dropLast(2)
Surprisingly, it works if you reverse the order and do the dropLast first:
print(myString.dropLast(2).dropFirst(2))

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.

Would this function be allowed in Swift (if it wouldn't crash the compiler)

I got this function, which is a minimised version of an actual use case:
func f (i:Int) -> <T> (x:T) -> T {
return { x in return x }
}
As you see I would like to compute a generic function based on some input.
But as you can see in Xcode or on swiftstub, this function crashes the compiler.
Does anybody know if Swift is supposed to support such definitions?
This no longer crashes the compiler when I try it on 1.2b3. However, it’s not valid syntax.
If you want to return a function where the type is determined up-front at the time f is called, this would do it:
func f<T>(i:Int) -> T -> T {
return { x in return x }
}
// need to tell the compiler what T actually is...
let g = f(1) as Int->Int
g(2) // returns 2
However, Swift does not support the ability to define “generic” closures, i.e. closures where the type is determined not on creation of the closure, but at the point when that closure is actually called. This would require higher-ranked polymorphism, something that isn’t currently available (though maybe in the future, who knows – would be a very nice feature to have). For now, the placeholders need to be fully determined at the call site.
Keep in mind that the "generic" nature of Swift generics is kind of a misnomer. The genericness is just a template notation; all genericness is compiled away at compile time - that is, all generics used in one part of your code are resolved (specified) by the way they are called in another part of your code.
But for that very reason, you can't return a generic function as a result of a function, because there is no way to resolve the generic at compile time.
So, while crashing the compiler is not nice (and Apple would like to know about it), your code should not compile either, and to that extent the compiler is correct to resist.

User input in Xcode Playground

I'm new to Swift and Xcode. I couldn't figure out how to take user input in Swift playground. I'm trying to write Swift equivalent of the following Python code:
def greet():
name = raw_input('What is your name?>')
print "Hello ", name
Is it possible to get user input in Swift playground?
Just use the ask() method which is available on Pad playgrounds