What does an underscore “_” mean in Swift?

2019-06-23 17:54发布

问题:

I just found this while browsing through the Swift module headers:

protocol _ObjectiveCBridgeable {

Similarly:

protocol _SequenceType {

Coming from an Objective-C background, this seems highly unconventional to me. The underscore _ usually implies that the concerned entity is private, and is often hidden in terms of header visibility. Why is it that in Swift they are publicly visible? Have the naming conventions changed for Swift?

回答1:

It seems that the conventions have changed as far as Swift is concerned, as evidenced by the following:

/// This protocol is an implementation detail of `SequenceType`; do
/// not use it directly.
///
/// Its requirements are inherited by `SequenceType` and thus must
/// be satisfied by types conforming to that protocol.
protocol _SequenceType {
}

As you can see, the underscore _ now seems to imply that the concerned entity is an 'implementation detail' of it's logical children.



回答2:

I believe (Swift dev team have stated on the forums that) there are specific limitations to Swift at the moment that force them to do two-part declarations for various protocols. Presumably eventually these will go away and the methods will be migrated into the non-underscore versions. So long as you only ever use the non-underscore ones, your code should recompile just fine when this happens, so for this reason you should never implement the _ versions directly.