6

I was working on a Swift tutorial and found that Swift has a strange way to handle multi-line statement.

First, I defined some extension to 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 doesn't work:

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

If I replace the reference to the lowercaseString property with a function call, it works again:

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

Is there anything in the Swift language specifications that prevent a property to be broken onto its own line?

Code at Swift Stub.

Code Different
  • 90,614
  • 16
  • 144
  • 163

3 Answers3

4

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

Code Different
  • 90,614
  • 16
  • 144
  • 163
2

This feels like a compiler bug, but it relates to the fact that you can define prefix, infix, and postfix operators in Swift (but not the . operator, ironically enough). I don't know why it only gives you grief on the property and not the function call, but is a combination of two things:

  • the whitespace before and after the . (dot) operator for properties (only)
  • some nuance of this ever growing language that treats properties differently than function calls (even though functions are supposed to first class types).

I would file a bug to see what comes out of it, Swift is not supposed to by pythonic this way. That said, to work around it, you can either not break the property from the type, or you can add a white space before and after the . .

let s2 = str.lowercaseString
    .replace("hello", withString: "goodbye")

let s3 = str
    . lowercaseString
    .replace("hello", withString: "goodbye")
Chris Conover
  • 8,889
  • 5
  • 52
  • 68
0

Using semicolons is not mandatory in swift. And I think that the problems with multiline statements in swift are because of optional semicolons.

Note that swift does not support multiline strings. Check here: Swift - Split string over multiple lines

So maybe swift cannot handle multiline statements. I am not sure about this and this could be one of the reasons so I would appreciate if anyone else can help regarding this issue.

Community
  • 1
  • 1
Ankit Goel
  • 6,257
  • 4
  • 36
  • 48