What Does the '@' Symbol Mean in Swift

What does @ (at symbol) do in Swift?

The @... represents an attribute, from SWIFT documentation:

Attributes provide more information about a declaration or type. There
are two kinds of attributes in Swift, those that apply to declarations
and those that apply to types.

You specify an attribute by writing the @ symbol followed by the
attribute’s name and any arguments that the attribute accepts:

You can read about them here.

In Swift, what does the ! symbol mean in a function signature?

This isn't quite a duplicate — there's some subtlety to implicitly unwrapped optionals in function signatures beyond their usage elsewhere.

You see implicitly unwrapped optionals in API imported from ObjC because that's the closest Swift approximation of an object that's expected to be there but which can be nil. It's a compromise for imported API — you can address these variables directly like in ObjC, and you can test them for nil using Swift optional syntax. (There's more about Apple's rationale for this in the Advanced Interoperability talk from WWDC14.) This pattern also applies to the IBAction declarations inserted by Interface Builder, since those methods are in effect getting called from ObjC code, too.

As you seem to have suspected, Swift wraps the possible nil in an optional when bridging from ObjC, but the ! in your function implementation's declaration unwraps the value so you can use it directly. (At your own risk.)

Since Swift 1.2 (Xcode 6.2 in Spring 2015), ObjC APIs can be annotated with nonnull and nullable, in which case the Swift interface to those APIs uses either a non-optional type or a fully optional type. (And since Swift 2.0 / Xcode 7.0, nearly all of Apple's APIs are audited to use nullability annotations, so their Swift signatures don't use much ! anymore.)

What's less well-known about this is that you're free to change the optionality of parameters when you implement your own Swift functions that get called by ObjC. If you want the compiler to enforce that sender in your action method can never be nil, you can take the ! off the parameter type. If you want the compiler to make sure you always test the parameter, change the ! to a ?.

What does an ampersand (&) mean in the Swift language?

It works as an inout to make the variable an in-out parameter. In-out means in fact passing value by reference, not by value. And it requires not only to accept value by reference, by also to pass it by reference, so pass it with & - foo(&myVar) instead of just foo(myVar)

As you see you can use that in error handing in Swift where you have to create an error reference and pass it to the function using & the function will populate the error value if an error occur or pass the variable back as it was before

Why do we use it? Sometimes a function already returns other values and just returning another one (like an error) would be confusing, so we pass it as an inout. Other times we want the values to be populated by the function so we don't have to iterate over lots of return values, since the function already did it for us - among other possible uses.

I hope that helps you!

What is the meaning of the '#' mark in swift language

Update (Swift 3.*...)

the default behavior of the first parameter’s signature was changed drastically. To understand how argument labels (ex. “external parameters”) and parameter names (ex. “local parameters”) work, please read the chapter “Function Argument Labels and Parameter Names” from the Apple’s Swift-book.

Some examples:

func someFunction(parameterName: Int) { parameterName }
someFunction(parameterName: 5) // argument label not specified

func someFunction(argumentLabel parameterName: Int) { parameterName }
someFunction(argumentLabel: 5) // argument label specified

func someFunction(_ parameterName: Int) { parameterName }
someFunction(5) // argument label omitted

There is no difference in this behavior between methods and functions.


Update (Swift 2.*)

The feature described below was deprecated, one need to write the parameter name twice to get the same behavior as with hash symbol before.


Update (examples)

For functions: when the function is called and purpose of some parameters is unclear, you provide external names for those parameters.

func someFunction(parameterName: Int) { parameterName }
someFunction(5) // What is the meaning of "5"?

func someFunction(externalParameterName parameterName: Int) { parameterName }
someFunction(externalParameterName: 5) // Now it's clear.

But if external and local names are the same, you just write a hash symbol before the parameter name.

func someFunction(#parameterName: Int) { parameterName }
// It's actually like:
// func someFunction(parameterName parameterName: Int) { parameterName }
someFunction(parameterName: 5)

For methods: by default first parameter name is only local (like by functions), but second and subsequent parameter names are both local and external (like as you write a hash symbol before the parameter name, this # is implicitly there):

class SomeClass {
func someMethodWith(firstParameter: Int, andSecondParameter: Int) { ... }
}
SomeClass().someMethodWith(5, andSecondParameter: 10)

You can use # (or add an explicit external name) for the first parameter of the method too, but it'll not match Objective-C-style calling.

class SomeClass {
func someMethodWith(#firstParameter: Int, andSecondParameter: Int) { ... }
}
SomeClass().someMethodWith(firstParameter: 5, andSecondParameter: 10)

Original answer

If you want to provide an external parameter name for a function
parameter, and the local parameter name is already an appropriate name
to use, you do not need to write the same name twice for that
parameter. Instead, write the name once, and prefix the name with a
hash symbol (#). This tells Swift to use that name as both the local
parameter name and the external parameter name.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/ru/book/swift-programming-language/id881256329?l=en&mt=11

What does the @ symbol represent in objective-c?

The @ character isn't used in C or C++ identifiers, so it's used to introduce Objective-C language keywords in a way that won't conflict with the other languages' keywords. This enables the "Objective" part of the language to freely intermix with the C or C++ part.

Thus with very few exceptions, any time you see @ in some Objective-C code, you're looking at Objective-C constructs rather than C or C++ constructs.

The major exceptions are id, Class, nil, and Nil, which are generally treated as language keywords even though they may also have a typedef or #define behind them. For example, the compiler actually does treat id specially in terms of the pointer type conversion rules it applies to declarations, as well as to the decision of whether to generate GC write barriers.

Other exceptions are in, out, inout, oneway, byref, and bycopy; these are used as storage class annotations on method parameter and return types to make Distributed Objects more efficient. (They become part of the method signature available from the runtime, which DO can look at to determine how to best serialize a transaction.) There are also the attributes within @property declarations, copy, retain, assign, readonly, readwrite, nonatomic, getter, and setter; those are only valid within the attribute section of a @property declaration.

Couldn't encode Plus character in URL + swift

Unfortunately, both CharacterSet.urlHostAllowed and CharacterSet.urlQueryAllowed contains + as allowed. And for historical reason, most web servers treat + as a replacement of whitespace (), so you need to escape +.

For such purpose, you may need to define your own CharacterSet:

extension CharacterSet {
static let rfc3986Unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
}

let emailAddressText = "mano+1@gmail.com"

let encodedEmail = emailAddressText.addingPercentEncoding(withAllowedCharacters:.rfc3986Unreserved)

print(encodedEmail!) //->mano%2B1%40gmail.com

What does # means in Apple Swift?

Check out the Shorthand External Parameter Names section of this doc: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/
Functions.html#//apple_ref/doc/uid/TP40014097-CH10-XID_256

Here is the excerpt in the event the above link does not work in the future:

Shorthand External Parameter Names

If you want to provide an external parameter name for a function parameter, and the local parameter name is already an appropriate name to use, you do not need to write the same name twice for that parameter. Instead, write the name once, and prefix the name with a hash symbol (#). This tells Swift to use that name as both the local parameter name and the external parameter name.

What does @() mean in Objective-C?

It's a pointer to an NSNumber object. It's called a boxed literal, because the mental picture is of putting a primitive value of expression inside into a "box", that is, an object.

See official documentation if in doubt. Note that pointer can be to a "real" NSNumber object or it can (theoretically, don't know whether this will work in practice) be a tagged pointer (see, e.g., my question).

Note that you can also do things like @"string" and @5, which will create constants in compile time. But you need parentheses to use something which is not a literal, e.g. @(2 + 3). Parentheses form can be used for any expression, even those that compiler cannot compute at compile-time (although if it can, it will just put an expression result into code).



Related Topics



Leave a reply



Submit