Multiline statement in Swift

情到浓时终转凉″ 提交于 2019-12-23 10:19:56

问题


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.


回答1:


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




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



回答3:


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.



来源:https://stackoverflow.com/questions/30633829/multiline-statement-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!