Multiline Statement in Swift

Multiline statement in Swift

This is definitely a compiler bug. Issue has been resolved in Xcode 7 beta 3.

Swift - Split string over multiple lines

Swift 4 includes support for multi-line string literals. In addition to newlines they can also contain unescaped quotes.

var text = """
This is some text
over multiple lines
"""

Older versions of Swift don't allow you to have a single literal over multiple lines but you can add literals together over multiple lines:

var text = "This is some text\n"
+ "over multiple lines\n"

Multiline expressions in swift

Just break the line before dot. I write this kind of code in other languages everyday.

class Foo {
var bar: Foo {
return self
}

var veryLongNameVariable: Foo {
return self
}

func method(i: Int, _: Int) -> Foo {
return self
}
}

let f = Foo()
let f2 = f
.bar
.method(3, 4)
.bar
.bar
.method(0, 2)
.veryLongNameVariable
.veryLongNameVariable

print(f2)

Swift Command Line Tool - Read multiple lines

You can call readLine() in a loop and exit the loop in a predefined way

var input: [String] = []

print("Enter text, finish by entering Q")
while let line = readLine(strippingNewline: true) {
if line.lowercased() == "q" { break }
input.append(line)
}

print(input)

Example

Enter text, finish by entering Q

a

b

c

q

["a", "b", "c"]

Program ended with exit code: 0

switch statement gone wrong - swift language

Let's start with your Obj-C implementation:

-(void)initialSite:(int)viewId 
{
UIViewController *viewController;
switch (viewId)
{
case 0:
{
viewController = self.initital;
NSString *star = [NSString stringWithFormat:@"Velkommen til %@'s Bog",[data valueForKey:@"navn"]];
self.navigationItem.title = star;
}
break;
case 1:
{
viewController = self.startSide;
NSString *start = [NSString stringWithFormat:@"%@'s Bog, start-side",[data valueForKey:@"navn"]];
self.navigationItem.title = start;
}
break;
}

[self showChildViewController:viewController];
}

Now this same snippet in Swift:

func initialSite(viewID:Int)
{
var viewController : UIViewController?

switch (viewID)
{
case 0:
viewController = self.initial
let navn = self.data["navn"] as? String
let star = "Velkommen til \(navn)'s Bog"
self.navigationItem.title = star

case 1:
viewController = self.startSide
let navn = self.data["navn"] as? String
let star = "\(navn)'s Bog, start-side"
self.navigationItem.title = star

default:
viewController = nil
// do nothing
}

self.showChildViewController(viewController)
}

The main thing you have to remember is the difference with var vs let. Typically you will use let to create things unless those things will have their value changed later, which you use var.

The other thing is the use of optionals, with the ? suffix. This is when the value may be nil (unset), otherwise it must contain a value.



Related Topics



Leave a reply



Submit