Swift Variable Declaration Meaning

Difference between variable declaration and definition in Swift

After doing much searching across the web for legitimate explanations, I have seemed to have found an answer:

The problem is that the two terms overlap to some extent. Definitions also serve as declarations, because they inject an identifier of a certain type to a scope. However, a declaration isn't a definition because it doesn't entail storage allocation for the declared object. To add to the confusion, the semantics of definitions and declarations is slightly different when applied to types and functions, as I will show momentarily. So let's look at a more detailed analysis of these two terms.

Here is the article: Declarations and Definitions.

The article gives further explanation and examples.

Swift variable declaration meaning

As of Swift 1.2, you can now use let with deferred assignment so you can use your if/else version:

let newUserInfo: [NSObject: NSObject]

if let tempUserInfo = error.userInfo as? [NSObject: NSObject] {
newUserInfo = tempUserInfo
} else {
newUserInfo = [:]
}

However, option 1 will not work, since there is a path where newUserInfo may not be set.

(note, as of 1.2b1, this doesn't work with global variables, only member and local variables, in case you try this out in a playground)

Alternatively, you could use the nil-coalescing operator to do it in one go, like this:

let newUserInfo = (error.userInfo as? [NSObject:NSObject]) ?? [:]

edit: Swift 1.2 added deferred assignment of let, enabling option 2 to be used with let now, but also changed the precedence of as? vs ??, requiring parens.

Pre-1.2 answer in case you have similar code you need to migrate:

Neither are particularly appealing if you ask me. In both cases, you have to have to declare newUserInfo with var, because you're not declaring and assigning it in one go.

I'd suggest:

let newUserInfo = error.userInfo as? [NSObject:NSObject] ?? [:]

What is the difference between declaration of a variable with ! and without !?

It's an implicitly unwrapped optional.

What does ?? mean on a variable declaration in Swift case let pattern matching?

In the context of pattern matching, x? is the “optional pattern” and equivalent to .some(x). Consequently, case x?? is a “double optional pattern” and equivalent to .some(.some(x)).

It is used here because UIApplication.shared.delegate?.window evaluates to a “double optional” UIWindow??, compare Why is main window of type double optional?.

Therefore

if case let presentationAnchor?? = UIApplication.shared.delegate?.window

matches the case that UIApplication.shared.delegate is not nil and the delegate implements the (optional) window property. In that case presentationAnchor is bound to the “doubly unwrapped” UIWindow.

See also Optional Pattern in the Swift reference:

An optional pattern matches values wrapped in a some(Wrapped) case of an Optional<Wrapped> enumeration. Optional patterns consist of an identifier pattern followed immediately by a question mark and appear in the same places as enumeration case patterns.

Difference between declaring a variable in ios Swift?

Here is a simple explanation

var indexArray = NSMutableArray()

As the above, indexArray variable can be any one , String , Int , ....... You didn't specifically give any type for that variable.

var indexArray : NSMutableArray = NSMutableArray()

In here you specifically give that indexArray is a NSMutableArray

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.

This example provides a type annotation for a variable called welcomeMessage, to indicate that the variable can store String values:

 var welcomeMessage: String

The colon in the declaration means “…of type…,” so the code above can be read as:

Declare a variable called welcomeMessage that is of type String.

The phrase “of type String” means “can store any String value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored.

The welcomeMessage variable can now be set to any string value without error:

 welcomeMessage = "Hello" 

You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name:

var red, green, blue: Double”

* Note *

It is rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it is defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference. In the welcomeMessage example above, no initial value is provided, and so the type of the welcomeMessage variable is specified with a type annotation rather than being inferred from an initial value.

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2
Prerelease).” iBooks. https://itun.es/us/k5SW7.l

Difference between various type of Variable declaration in swift

Array is a swift type where as NSArray is an objective C type. NS classes support dynamic-dispatch and technically are slightly slower to access than pure swift classes.

1) var arr = NSArray()

arr is an NSArray() here - you can re-assign things to arr but you can't change the contents of the NSArray() - this is a bad choice to use IMO because you've put an unusable array into the variable. I really can't think of a reason you would want to make this call.

2) var arr = NSMutableArray()

Here you have something usable. because the array is mutable you can add and remove items from it

3) var arr = Array()

This won't compile - but var arr = Array<Int>() will.

Array takes a generic element type ( as seen below)

public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer {
/// Always zero, which is the index of the first element when non-empty.
public var startIndex: Int { get }
/// A "past-the-end" element index; the successor of the last valid
/// subscript argument.
public var endIndex: Int { get }
public subscript (index: Int) -> Element
public subscript (subRange: Range<Int>) -> ArraySlice<Element>
}

4) var arr : NSMutableArray?

You are defining an optional array here. This means that arr starts out with a value of nil and you an assign an array to it if you want later - or just keep it as nil. The advantage here is that in your class/struct you won't actually have to set a value for arr in your initializer

5) var arr : NSMutableArray = []

Sample Image

It sounds like you are hung up on confusion about Optional values.

Optional means it could be nil or it could not

When you type something as type? that means it is nil unless you assign it something, and as such you have to unwrap it to access the values and work with it.

Swift variable declaration with closure

Syntax

As @findall said in the comments, you are basically creating a function and executing it.

To clarify the syntax, I'll try to create an example in JavaScript.

Consider this code snippet:

Example #1

//creates a global variable
var globalString = "Very important global string";

This string will be created and stored in memory as soon as this line of code is interpreted. Now compare it to this other implementation:

Example #2

//also creates a global variable 
var globalString = function() {
return "Very important global string";
};

The second implementation does not create a string, but creates a function that ultimately produces a string.

In Swift, when you declare a variable with the {...}() syntax, you are actually doing something similar to Example #2.



Use case

When would it be useful to declare a variable in such way? When the declaration would require some extra setup to take place.

In the example posted in the question, an NSDateFormatter may need a few extra steps to be instantiated the way your app expects it to behave. In other words:

class ThisClass {
//if you do this, you'll then have to configure your number formatter later on
static var dateFormatter = NSDateFormatter()

func userFormatter() {
//you probably want this setup to take place only once
//not every time you use the formatter
ThisClass.dateFormatter.dateFormat = "yyyy-MM-dd"

//do something with the formatter
}
}

This example is quite nicely replaced by:

class ThisClass {
static var dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()

func userFormatter() {
//do something with the formatter with no setup needed!
}
}

Do you need to declare datatype of a variable in Swift?

var myVar: Int = 50

Or:

var myVar = 50

They are absolutely equivalent. The : Int is unnecessary because you are assigning 50 right there in the declaration, so Swift infers that this is to be an Int variable.

If you are going to assign as part of the declaration, the only time you need to supply the type is when the type is surprising. For example:

var myChar : Character = "s"

If you don't say Character, you'll get a String.



Related Topics



Leave a reply



Submit