Why can the Objective-C class and protocol have the same name, but Swift cannot, what is the difference in language implementation?

Swift, Can not compile, the compiler will report an error directly.

protocol Test {}

struct Test {}


// Swift compile output:

// Untitled.swift:4:8: error: invalid redeclaration of 'Test' struct Test {}

// Untitled.swift:2:10: note: 'Test' previously declared here protocol Test {}

Objective-C, can be compiled successfully, for example NSObject is the name of the class, it is also the name of the protocol

#import <Foundation/Foundation.h>

@protocol Test
@end

@interface Test
@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSLog(@"Hello word");
    }
}
// Objective-C output
// 2018-03-11 23:14:20.341 Untitled[34921:1272761] Hello word
+4
source share
1 answer

Objective-C and Swift have different name resolution schemes that cause this.

  • Objective-C , , . ( , , , .) - . , - : Foo Foo, Foo - @protocol(Foo). .
  • Swift, , . , , Foo Foo, .

, - , Swift, enum s/struct s/class es , , ; Swift, . , , , struct Test protocol Test : <name-of-your-module>.Test

, struct Test protocol Test , , . ,

struct ExpressibleByStringLiteral {}

, , . ExpressibleByStringLiteral , , stdlib, Swift.ExpressibleByStringLiteral:

struct ExpressibleByStringLiteral {}
struct S1 : ExpressibleByStringLiteral {} // error: inheritance from non-protocol type 'ExpressibleByStringLiteral'

struct S2 : Swift.ExpressiblyByStringLiteral {} // need to add methods to satisfy the protocol

Swift. , .

+5

Source: https://habr.com/ru/post/1694737/


All Articles