Multiline statement in Swift

I was working on a Swift tutorial and found that Swift has a weird way of handling a multi-line statement.

First, I defined some extension of the standard String class:

 extension String { func replace(target: String, withString: String) -> String { return self.stringByReplacingOccurrencesOfString(target, withString: withString) } func toLowercase() -> String { return self.lowercaseString } } 

This works as expected:

 let str = "HELLO WORLD" let s1 = str.lowercaseString.replace("hello", withString: "goodbye") // -> goodbye world 

This does not work:

 let s2 = str .lowercaseString .replace("hello", withString: "goodbye") // Error: could not find member 'lowercaseString' 

If I replace the reference to the lowercaseString property lowercaseString function call, it will work again:

 let s3 = str .toLowercase() .replace("hello", withString: "goodbye") // -> goodbye world 

Is there anything in the Swift language specs that prevent a property from being split on its own line?

Code in Swift Stub .

+5
source share
3 answers

This is definitely a compiler error. The problem is resolved in Xcode 7 beta 3.

+4
source

This seems like a compiler error, but this is because you can define the prefix, infix, and postfix operators in the Swift statement (but not in the statement), paradoxically). I don’t know why this only gives you sadness about ownership, not a function call, but it is a combination of two things:

  • spaces before and after. (dot) for properties (only)
  • some nuance of this ever-growing language that treats properties differently than function calls (although functions are assumed for types of the first class).

I would put an error to see what comes of it, Swift should not be pythonic this way. However, to get around this, you can either not break the property from the type, or add a space before and after . .

 let s2 = str.lowercaseString .replace("hello", withString: "goodbye") let s3 = str . lowercaseString .replace("hello", withString: "goodbye") 
+2
source

Using semicolons is optional for quick. And I think that problems with multi-line statements in swift are due to optional semicolons.

Please note: swift does not support multiline strings. Check here: Swift - split a line into multiple lines

Therefore, it is possible that swift cannot handle multi-line statements. I am not sure about this, and this may be one of the reasons, so I would appreciate it if someone else could help solve this problem.

0
source

All Articles