What is the meaning of ?? in swift?
Nil-Coalescing Operator
It's kind of a short form of this. (Means you can assign default value nil
or any other value if something["something"]
is nil
or optional)
let val = (something["something"] as? String) != nil ? (something["something"] as! String) : "default value"
The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.
The nil-coalescing operator is shorthand for the code below:
a != nil ? a! : b
The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.
If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.
The example below uses the nil-coalescing operator to choose between a default color name and an optional user-defined color name:
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"
See section Nil-Coalescing Operator here
What does \. mean in Swift
See Key-Path Expression in the Expressions section of the Language Reference in The Swift Programming Language.
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 is the meaning of 'Swift are Unicode correct and locale insensitive' in Swift's String document?
To expand on @matt's answer a little:
The Unicode Consortium maintains certain standards for interoperation of data, and one of the most well-known standards is the Unicode string standard. This standard defines a huge list of characters and their properties, along with rules for how those characters interact with one another. (Like Matt notes: letters, emoji, combining characters [letters with diacritics, like é
, etc.)
Swift strings being "Unicode-correct" means that Swift strings conform to this Unicode standard, offering the same characters, rules, and interactions as any other string implementation which conforms to the same standard. These days, being the main standard that many string implementations already conform to, this largely means that Swift strings will "just work" the way that you expect.
However, along with the character definitions, Unicode also defines many rules for how to perform certain common string actions, such as uppercasing and lowercasing strings, or sorting them. These rules can be very specific, and in many cases, depend entirely on context (e.g., the locale, or the language and region the text might belong to, or be displayed in). For instance:
- Case conversion:
- In English, the uppercase form of
i
("LATIN SMALL LETTER I" in Unicode) isI
("LATIN CAPITAL LETTER I"), and vice versa - In Turkish, however, the uppercase form of
i
is actuallyİ
("LATIN CAPITAL LETTER I WITH DOT ABOVE"), and the lowercase form ofI
("LATIN CAPITAL LETTER I") isı
("LATIN SMALL LETTER DOTLESS I")
- In English, the uppercase form of
- Collation (sorting):
- In English, the letter
Å
("LATIN CAPITAL LETTER A WITH RING ABOVE") is largely considered the same as the letterA
("LATIN CAPITAL LETTER A"), just with a modifier on it. Sorted in a list, words starting withÅ
would appear along with otherA
words, but beforeB
words - In certain Scandinavian languages, however,
Å
is its own letter, distinct fromA
. In Danish and Norwegian,Å
comes at the end of the alphabet:... X, Y, Z, Æ, Ø, Å
. In Swedish and Finnish, the alphabet ends with:... X, Y, Z, Å, Ä, Ö
. For these languages, words starting withÅ
would come afterZ
words in a list
- In English, the letter
In order to perform many string operations in a way that makes sense to users in various languages, those operations need to be performed within the context of their language and locale.
In the context of the documentation's description, "locale-insensitive" means that Swift strings do not offer locale-specific rules like these, and default to Unicode's default case conversion, case folding, and collation rules (effectively: English). So, in contexts where correct handling of these are needed (e.g. you are writing a localized app), you'll want to use the Foundation extensions to String methods which do take a Locale
for correct handling:
localizedUppercase
/uppercased(with locale: Locale?)
over justuppercased()
localizedLowercase
/lowercased(with locale: Locale?)
over justlowercased()
localizedStandardCompare(_:)
/compare(_:options:range:locale:)
over just<
among others.
What the meaning of question mark '?' in swift?
You can use
if
andlet
together to work with values that might be
missing. These values are represented asoptionals
. Anoptional
value either contains a value or containsnil
to indicate that the
value is missing. Write a question mark (?) after the type of a value
to mark the value asoptional
.If the optional value is
nil
, the conditional isfalse
and the code in
braces is skipped. Otherwise, the optional value is unwrapped and
assigned to the constant afterlet
, which makes the unwrapped value
available inside the block of code.
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/pk/jEUH0.l
For Example:
var optionalString: String? = "Hello"
optionalString == nil
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
In this code, the output would be Hello! John Appleseed
. And if we set the value of optionalName
as nil
. The if
conditional result would be false
and code inside that if
would get skipped.
What is the meaning of '_ in print()' in Swift?
This statement is using trailing closure syntax. The stuff between {
and }
is actually a closure that is passed to UIAlertAction
to be called later when the event happens. When the closure is called, it will be passed the UIAlertAction
object that was created.
let cancelAlertAction = UIAlertAction (title : cansal , style : .cancel) {
_ in print("cancel") \\ i don't understand this line . its just a print or somthing else . why i cant use print here.
}
If you intend not to use the alert action, then you need the _ in
to tell Swift that you are ignoring the UIAlertAction
and doing nothing with it. You are saying, I know there is a parameter but I am ignoring it.
If you don't specify the _ in
, Swift infers your closure type to be of type () -> ()
which means it takes nothing and produces nothing. This doesn't match the type of the closure you are expected to provide which is (UIAlertAction) -> Void
(takes a UIAlertAction
and returns nothing).
It is usually written like this:
let cancelAlertAction = UIAlertAction (title : cansal , style : .cancel) { _ in
print("cancel")
}
which makes it clearer that the _ in
is the closure parameter syntax and not directly related to the print
statement.
what do _ and in mean in Swift programming language?
_
means don't name that thing. It can be used in a number of places. In your case, it is saying ignore the variable being passed into the closure. The code you gave is ignoring all parameters but you can also just ignore some parameters.
in
is the start of the implementation of the closure. In your example code, the implementation of the closure is empty.
Overall, that line is defining a closure called "done" that takes an Optional NSError (NSError?
), NSData (NSData
), and Optional NSString (NSString?
) and returns nothing (-> ()
). The actual implementation of the closure does nothing.
What is the meaning of in in Swift?
It is part of swift's closure syntax. Because the parameters and a return type of a closure are inside the curly braces in
is used to separate them from the body.
What's the meaning of as!,init? in swift?
Use
as
When you believe that a constant or variable of a certain class type may actually refer to an instance of a subclass.
Using
as?
will always return an optional value and if the downcasting wasn't possible it will return nil.
Using
as!
is forced unwrapping of the value. Use "as!" when you're sure that the optional has a value.
init?
is used to write fail-able initialisers. In some special cases where initialisations can fail you write fail-able initiasers for your class or structure.
Related Topics
Change Tabview Indicator Swiftui
Use a Function to Find Common Elements in Two Sequences in Swift
Converting .M4A File to .Aiff Using Audioconverter Swift
Evaluate Bool Property of Optional Object in If Statement
How Is a Return Value of Anyobject! Different from Anyobject
Uitesting Xcode 7: How to Tell If Xcuielement Is Visible
Swift 4 Codable - API Provides Sometimes an Int Sometimes a String
Use Uipangesturerecognizer to Drag Uiview Inside Limited Area
Swift Bindings Won't Work Xcode 6 Beta 5
Animate the Fractioncomplete of Uiviewpropertyanimator for Blurring the Background
Count Number of Decimal Places in a Float (Or Decimal) in Swift
How to Get Data from Observedobject with Onreceive in Swiftui
Swift Programming Nserrorpointer Error etc
How to Get Date and Time to Show a Clock in Uilabel
Understanding the Removerange(_:) Documentation
How to Make Alphabetically Section Headers in Table View with a Mutable Data Source