-2

I come from JS so I am not sure about string literals.

I have the following syntax in my swift

[GMSServices provideAPIKey:@"ABCXYZ"];

if I remove @ from the above, swift throws the following error String literal must be prefixed by '@'

Can someone explain me why I am getting this error and what are string literals? This answer wasn't helpful in above context: What does the @ prefix do on string literals in C#

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
Rahul Patel
  • 63
  • 1
  • 11

1 Answers1

0

First of all, do not post API keys on the Internet. I have edited your question to remove the key, but it is still visible in the question history.

Anyway, the code you quoted is Objective-C code, not Swift code. That code declares an NSString literal. NSString is an Objective-C class. In contrast to a plain C string, the NSString class provides many APIs for using and manipulating strings, and the Objective-C runtime manages NSString memory so you don't have to.

In Swift, the equivalent code is

GMSServices.provideAPIKey("ABCXYZ")

Here, we are using a Swift String literal, which is similar to NSString, with many APIs and with automatic memory management, but we don't need an @ prefix because Swift is not a superset of C.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • That key contained only a small part of actual key. I mean it won't work for others but thanks for removing it :) – Rahul Patel May 08 '20 at 23:50
  • if I replace `[GMSServices provideAPIKey:@"ABCXYZ"];` with GMSServices.provideAPIKey("ABCXYZ") in my code. it gives the error `Property 'provideAPIKey' not found on object of type 'GMSServices'` – Rahul Patel May 08 '20 at 23:58