In Swift, What Does This Specific Syntax Mean

in Swift, what does this specific syntax mean?

The old Swift 1 syntax is based on the way you deal with option sets in C and Objective-C: you store an option set in an integer type and use bitwise operators (| and & and ~) to manipulate them. So .UsernameAndPassword | .LogInButton means an option set in which both the .UsernameAndPassword and the .LogInButton options are included. In the old syntax, you use nil to represent an empty option set (in which no options are included), which is not obvious based on the syntax for a non-empty set.

Chris Lattner described the changed syntax in WWDC 2015 Session 106: What's New in Swift. First he describes the problems with the old syntax:

The problem is, when you get to the other syntaxes you end up using, it is a bit less nice. You create an empty-option set with nil -- it doesn't make sense because option sets and optionals are completely different concepts and they're conflated together. You extract them with bitwise operations, which is a pain and super error-prone, and you can get it wrong easily.

Then he describes the new approach:

But Swift 2 solves this. It makes option sets set-like. That means option sets and sets are now formed with square brackets. That means you get empty sets with an empty set of square brackets, and you get the full set of standard set API to work with option sets.

The reason the new syntax works is because OptionSetType conforms to the ArrayLiteralConvertible protocol (indirectly, by conforming to SetAlgebraType). This protocol allows a conforming object to be initialized using an array literal, by having an init that takes a list of elements.

In the new Swift 2 syntax, [ .UsernameAndPassword, .LogInButton ] represents an option set containing both the .UsernameAndPassword and the .LogInButton options. Note that it looks just like the syntax by which you can initialize a plain old Set: let intSet: Set<Int> = [ 17, 45 ]. The new syntax makes it obvious that you specify an empty option set as [].

What does this syntax mean in Swift?

{} declares a closure, which is anonymous function. Everything between { and } is a function body. Since closure defined in provided code does not have arguments it can be executed as regular function by (). { .. }() is just defining and immediately executing of anonymous function.

In a body of a function there is a call of instantiateViewControllerWithIdentifier("Play") which returns AnyObject. As viewController variable (var) expected to ba a type of ViewController, we cast AnyObject result of instantiateViewControllerWithIdentifier as ViewController

As for statusBarStyle, UIStatusBarStyle is an enum. .Default is one of enum's cases. It can be written alternatively as var statusBarStyle = UIStatusBarStyle.Default. The code that goes in the { ... } is a way to declare getter and setter behavior. In this particular case there is only one behavior didSet defined, which means as soon as value of UIStatusBarStyle updated (which is possible, as it is var), call function setNeedsStatusBarAppearanceUpdate. There are other getters & setters keywords that you may read about in Swift Book — https://itunes.apple.com/us/book/swift-programming-language/id881256329 such as get, set, willSet.

What function does as in the Swift syntax have?

The as keyword is used for casting an object as another type of object. For this to work, the class must be convertible to that type.

For example, this works:

let myInt: Int = 0.5 as Int // Double is convertible to Int

This, however, doesn't:

let myStr String = 0.5 as String // Double is not convertible to String

You can also perform optional casting (commonly used in if-let statements) with the ? operator:

if let myStr: String = myDict.valueForKey("theString") as? String {
// Successful cast
} else {
// Unsuccessful cast
}

In your case, touches is (I'm assuming from the anyObject() call) an NSSet. Because NSSet.anyObject() returns an AnyObject?, you have to cast the result as a UITouch to be able to use it.

In that example, if anyObject() returns nil, the app will crash, because you are forcing a cast to UITouch! (explicitly unwrapping). A safer way would be something like this:

if let touch: UITouch = touches.anyObject() as? UITouch {
// Continue
}

Swift syntax, and understanding certain parts of the language

Okay, because your question hasn't been closed as too broad, and because it has upvotes, I'll try to give you at least a start on what I think you were actually asking...

Where to find out what this stuff means:

First, for Swift, you want to read The Swift Programming Language: A Swift Tour. This will give you a really good beginner's overview of the language and how to use it. It includes a downloadable Swift Playground that includes the entire tour and allows you to try things out and practice what you're learning.

Next, when you see something, like URLRequest, you can look it up in the Developer Documentation. To get to this documentation, you can search on the name and the text "developer documentation". Alternatively, you can go to the Developer site and search from there. Finally, you can look it up in Xcode's documentation window: from the Xcode menu, Window -> Developer Documentation.

Often, the developer site will also provide sample code as well. This is really cool, 'cause you can download it, play with it, and per the license information, use it in your own code. This code also usually has remarks and descriptions throughout that help you understand what it's doing. The sample code is a really good way of learning when and how to use the different functions you come across!

Now, having said that, the documentation itself (separate from the sample code) can be quite confusing for a beginner. However, as you gain experience, you'll understand more of what it's trying to tell you.

What the documentation tells you:

Let's walk through the documentation for URLRequest:

URLRequest Reference Documentation

At the top, you see that this is a Structure, not a Class. In the Swift Tour, you'll learn the difference.

Under the name URLRequest, you see a description. The description here is usually about as clear as mud for a newbie. However, some descriptions are followed by detailed and really good information about the item. For an example of this, take a look at the UIViewController documentation.

At the right side of the page, you find when the item became available (URLRequest has been available since iOS 7, for example), which framework you need to import to use it (Foundation, here), and links to other information.

"Topics" lists the properties and functions you can use to do various things. For example, you might want to "create a request" or "work with a cache policy" using an URLRequest object.

URLRequest "Topics" Section

"Relationships" gives you information about inheritance and protocols to which the item conforms. These items show other properties and methods that can be used in a given object. Again, these can be confusing for beginners, but you'll eventually get it. For example, URLRequest conforms to Equatable. That means you can compare urlRequest1 == urlRequest2 or != as well.

URLRequest "Relationships" Section

Finally, the "See also" section shows you other things that are related to this one. You can use this section to learn more about items you might want to use along with the one you're currently viewing.

URLRequest "See also" Section

How your example breaks down:

The particular example you picked is creating or "instantiating" a new URLRequest object:

URLRequest(url: NSURL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")! as URL)

Therefore, it would use the "topic" regarding "creating a request". That shows us:

init(url: URL, cachePolicy: URLRequest.CachePolicy, timeoutInterval: TimeInterval)
Creates and initializes a URL request with the given URL and cache policy.

Now, it turns out that the "creating a request" topic is actually missing a function here. Go to a Swift playground, and enter URLRequest(, stopping at the left paren. You'll see that two items appear: one that shows the above (without the init part), and one that just shows (url: URL). I'll get back to that in a sec...

Newbies might not realize they don't need to use the init part shown in the documentation. You can use URLRequest.init(...) if you want, but you can simplify that to just URLRequest(...), with the dots representing what goes inside, of course. So, back to the missing initializer, it should appear in the documentation as:

init(url: URL)

That's the one your example is actually using, so I'll cover it going forward.

The parts that go inside the parentheses are "parameters" or "arguments". (There's a subtle difference, but many developers use these two terms interchangeably.) You'll learn in the Swift Tour that if a label is required, it'll be there; otherwise, it'll have an underscore (_). So, here, you must have a label for url:. If you type this in Xcode 9, you'll get:

URLRequest(url: URL)

Xcode provides the labels you need to have, and it's giving you hints as to how to fill in the blanks: at the url: label, you need to provide a URL-type object.

The labels represent the variable name you'd use to access that piece of information, if you were writing a function yourself. Since this is a Foundation-provided function, it's the variable name the URLRequest initialization function would use inside itself, hidden (or "encapsulated") away from your eyes, but necessary to create a URLRequest.

Now, your example can be broken into two parts. Since they needed a URL object, they created it inside the url: argument. This example could be broken down to something like the following:

let nsURL = NSURL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")! as URL
let request = URLRequest(url: nsURL)

The NSURL command, though, is actually from Objective-C. (As a rule of thumb, anything starting with NS is coming from Objective-C. As these get converted into pure Swift, the NS goes away.) Swift has it's own version of NSURL now, so the example code is "casting" or changing the NSURL into an URL at the end. This could be rewritten entirely in Swift as:

let url = URL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
let request = URLRequest(url: url!)

What the question and exclamation marks mean:

The question mark indicates an "optional" value, while the exclamation point is "force-unwrapping an optional" value. This is discussed in the tour, but is probably one of the most confusing aspects of Swift 'til you finally get it. Consider this example:

// This is supposed to be a String value - but it's empty right now ("nil").
// Therefore, I put a '?' on the type name to tell Swift that it's a String,
// but it could be nil (meaning it's value is "optional" - it may be there or not)
let nilString: String? = nil

// I'll go ahead and give the string a value here:
nilString = "I'm not nil anymore."

// Now, I'll use this String value - but I told Swift it might be empty!
// I can tell Swift that I'm CERTAIN a value is present by "force unwrapping" it:
// that is, indicating I'm sure it's not nil by adding a '!'
let newString = nilString! + "testing"

If I had tried to use the value while it was still nil, Swift would yell at me: fatal error: unexpectedly found nil while unwrapping an Optional value.

Okay. I believe I've covered most of what you were actually asking, so ending my "book" here before the SO masters kick me out! You can make this the answer, if I've guessed right at what you were seeking. Either way, read the Swift Tour, and go forth young padawan in your coding career!

What does the [something] syntax in Swift mean when working with closures?

That [bar] part is a capture list.

It instructs the closures as how values should be captured. When you enter variables in the bracket right before the keyword in, the closure is no longer referencing the original variables, instead the closure creates its own copy within the closure block.

What does in mean in Swift?

As like in your code example using in afther newValue let`s Swift and you know the return value of process is going happen on newValue so it is more like a symbol or flag called: "token" to you and to CPU that work is going happen on newValue because you put it before in, for example you gave name to onChange modifier with using newValue in, you will get updated value for name if get any new update, also note you can use $0 instead of newValue in and works same.



.onChange(of: name) { newValue in
return print("Name changed to \(name)!")
}

Or:

.onChange(of: name) { 
print("Name changed to \($0)!")
}

Both are the same it depends how you like it.

Another example for better understanding:

let arrayOfInt: [Int] = [1, 2, 3]


let arrayOfString: [String] = arrayOfInt.map({ value in return value.description })
let arrayOfString: [String] = arrayOfInt.map({ $0.description })

For example we have an arrayOfInt and we want create a String array of it, for this work we can use map, and again like last example we used in in 2 way. in the first one as: value in and in the second on as $0. I recommend you work and learn more about closure in Swift/SwiftUI they are very important, without knowing them well, we cannot have good understanding of codes in iOS.

Also do not forget to attention to word of return right after in you can type and use or not use it, Swift is Smart enough to understand because of inference, but if you use it, it make your code much more easy and simple to read and better in syntax of code.

Is @IBAction just a syntax in Swift or does @Something mean a particular thing in Swift?

These are attributes in swift.They have some special meaning for compiler.For eg: @UIApplicationMain synthesize main.swift file by compiler as entry point for application.From swift guide

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.

NSApplicationMain
Apply this attribute to a class to indicate that it is the application delegate. Using this attribute is equivalent to calling
the NSApplicationMain function and passing this class’s name as the
name of the delegate class.

If you do not use this attribute, supply a main.swift file with a main
function that calls the NSApplicationMain function. For example, if
your app uses a custom subclass of NSApplication as its principle
class, call the NSApplicationMain function instead of using this
attrib

Here is whole list of attributes in swift

From apple swift blog

In Xcode, Mac templates default to including a “main.swift” file, but
for iOS apps the default for new iOS project templates is to add
@UIApplicationMain to a regular Swift file. This causes the compiler
to synthesize a main entry point for your iOS app, and eliminates the
need for a “main.swift” file.

Alternatively, you can link in an implementation of main written in
Objective-C, common when incrementally migrating projects from
Objective-C to Swift.

write code in main.swift.It will work as enty point for application

//main.swift
import Foundation
import UIKit

UIApplicationMain(C_ARGC, C_ARGV,nil, NSStringFromClass(AppDelegate))

swift syntax using var ={}() meaning?

What you see there is a closure for setting the initial value of the variable. A closure can be described as an anonymous code block.

This is what your code looks like:

var productLines: [ProductLine] = { return ProductLine.productLines() }()

Let me expand your code like this:

var productLines: [ProductLine] = { () -> [ProductLine] in 
return ProductLine.productLines()
}()

The closure itself consists of the following code

{ () -> [ProductLine] in 
return ProductLine.productLines()
}

The two round brackets () are used to execute the closure.
So what you see is not a computed property. You are therefore able to change the value of productLines like this afterwards:

productLines = [ProductLine]()

If it was a computed property instead, you would get an error like this one:

Cannot assign to property: productLines is a get-only property

What does the parentheses mean in this var declaration?

The parenthesis is a way of calling the initialiser.

This is equivalent to:

var completionHandlers: [(String) -> Void] = []

Another way you will see it is:

var completionHandlers: [(String) -> Void] = .init()

You see it when initialising empty collections because if, for example you had:

var someVariable = ["hello", "world"]

The compiler would be able to infer the type of someVariable to be [String] because it knows the type of the contents. but You can't initialise an empty array like this because there is no information about the type. so [(String) -> Void]() is a way of providing the type to the empty initialiser.

The general recommendation in Swift is to use Type Inference where the type of the variable is inferred from it's initial value:

let intVariable = 3
let stringVariable = "Hello"
//etc

The style of code in your question follows this.

But in some cases with more complex types this can slow down the compiler, so many people are more explicit with their variable declarations.

let intVariable: Int = 3
let stringVariable: String = "Hello"

It's a matter of taste (and argument).



Related Topics



Leave a reply



Submit