本文介绍了Swift 语法,理解语言的某些部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了 Swift 编程语言的基础知识,例如变量、类、函数等.我不明白的是,当我开始尝试构建应用程序时,是如何设置函数的结构.我猜功能,或者我在下面列出的.我会尽我所能详细说明.

我想了解人们是如何知道的,或者在您尝试完成某事时应该从哪里了解该放什么.

例如,我在 Google 上搜索了一个 HTTP 调用,然后出现了以下代码:

let request = URLRequest(url: NSURL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")!作为 URL)做 {//执行请求var 响应:AutoreleasingUnsafeMutablePointer?= 零让数据 = 尝试 NSURLConnection.sendSynchronousRequest(请求,返回:响应)

我完全迷失了:

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

你在哪里阅读以了解何时使用诸如 URLRequest 之类的东西,或者如何或何时将 url: 放在它前面.尽管这只是一个示例,但我注意到在构建 swift 应用程序时你们使用了诸如 NSUrl、NSObject、URLRequest 之类的东西.在文档中我还没有了解这些东西.我不明白你们怎么知道什么时候放问号?",或者你如何像上面的例子那样格式化你的函数.

如果我问得不对,我总是可以解释更多.

如果您知道我可以在网上搜索什么以便我知道我想学习什么,那将会很有帮助.或者一本教你 UIWindows 以及使用 NSObject 和 UIWindows 之类的东西的基本功能的书,这会很有帮助.

难点在于理解 API 文档.如果您无法理解 api 文档和语法.你怎么能学会.我想它更容易,有时可以通过实例学习.

解决方案

好的,因为你的问题还没有说得太宽泛,而且因为它有赞成票,我会尝试至少给你一个开始我想你实际上是在问...

在哪里可以找到这些东西的含义:

首先,对于 Swift,您需要阅读

在顶部,您会看到这是一个 Structure,而不是一个 Class.在 Swift Tour 中,您将了解不同之处.

在名称 URLRequest 下,您会看到一个描述.对于新手来说,这里的描述通常就像泥巴一样清晰.但是,一些描述之后是有关该项目的详细且非常好的信息.有关此示例,请查看

关系"为您提供有关项目所遵循的继承和协议的信息.这些项目显示了可以在给定对象中使用的其他属性和方法.同样,这些对于初学者来说可能会令人困惑,但您最终会明白的.例如,URLRequest 符合 Equatable.这意味着您也可以比较 urlRequest1 == urlRequest2!= .

最后,另请参阅"部分会向您展示与此相关的其他内容.您可以使用此部分来详细了解您可能想要与当前正在查看的项目一起使用的项目.

您的示例如何分解:

您选择的特定示例是创建或实例化"一个新的 URLRequest 对象:

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

因此,它将使用有关创建请求"的主题".这向我们展示了:

init(url: URL, cachePolicy: URLRequest.CachePolicy, timeoutInterval: TimeInterval)使用给定的 URL 和缓存策略创建并初始化 URL 请求.

现在,事实证明创建请求"主题实际上在这里缺少一个函数.转到 Swift 游乐场,然后输入 URLRequest(,在左括号处停止.您会看到出现两个项目:一个显示上述内容(没有 init 部分),还有一个只显示 (url: URL) 的.我会在一秒钟内回到那个......

新手可能没有意识到他们不需要使用文档中显示的 init 部分.如果需要,您可以使用 URLRequest.init(...),但您可以将其简化为 URLRequest(...),其中的点代表内部内容, 当然.因此,回到缺少的初始化程序,它应该在文档中显示为:

init(url: URL)

这就是您的示例实际使用的那个,所以我会继续介绍它.

括号内的部分是参数"或参数".(有一个细微的区别,但许多开发人员交替使用这两个术语.)您将在 Swift Tour 中了解到,如果需要标签,它就会在那里;否则,它会有一个下划线 (_).所以,在这里,你必须有 url: 的标签.如果你在 Xcode 9 中输入这个,你会得到:

URLRequest(url: URL)

Xcode 提供了您需要的标签,并且它会提示您如何填空:在 url: 标签处,您需要提供一个 URL-类型对象.

如果您自己编写函数,标签代表您用来访问该信息的变量名称.由于这是一个 Foundation 提供的函数,它是 URLRequest 初始化函数将在自身内部使用的变量名称,隐藏(或封装")远离您的眼睛,但对于创建 URLRequest 是必要的.

现在,您的示例可以分为两部分.由于他们需要一个 URL 对象,他们在 url: 参数创建了它.此示例可以分解为以下内容:

let nsURL = NSURL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")!作为网址让请求 = URLRequest(url: nsURL)

不过,NSURL 命令实际上来自 Objective-C.(根据经验,任何以 NS 开头的东西都来自 Objective-C.随着它们被转换成纯 Swift,NS 消失了.)Swift 有它自己的现在是 NSURL 的版本,所以示例代码在最后转换"或将 NSURL 更改为 URL.这可以完全用 Swift 重写为:

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

问号和感叹号的含义:

问号表示可选"值,而感叹号表示强制展开可选"值.这在导览中进行了讨论,但这可能是 Swift 中最令人困惑的方面之一,直到您最终掌握它为止.考虑这个例子:

//这应该是一个字符串值 - 但现在它是空的(nil").//因此,我放了一个 '?'在类型名称上告诉 Swift 它是一个字符串,//但它可能为零(意味着它的值是可选的"——它可能存在也可能不存在)让 nilString: 字符串?= 零//我会继续在这里给字符串一个值:nilString = "我不再是零了."//现在,我将使用这个 String 值 - 但我告诉 Swift 它可能是空的!//我可以通过强制解包"告诉 Swift 我确定存在一个值://也就是说,通过添加一个 '!' 来表明我确定它不是 nil让 newString = nilString!+测试"

如果我在它仍然是 nil 时尝试使用该值,Swift 会冲我大喊:fatal error:unwrapping an Optional value 时意外发现 nil.

好的.我相信我已经涵盖了你真正要问的大部分内容,所以在 SO 大师把我踢出去之前结束我的书"!如果我猜对了您正在寻找的内容,您可以将其作为答案.无论哪种方式,阅读 Swift Tour,在您的编码生涯中继续年轻的学徒!

I have read the basic's on the Swift programming language such as variables, classes, functions etc. What I don't understand is when I start trying to build an application, is the structure of how you set up a function. I am guessing function, or what I list below. I will elaborate the best I can.

I'd like to understand how people know, or where to learn what to put when your trying to accomplish something.

For example I Googled making a HTTP call and this code came up:

let request = URLRequest(url: NSURL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")! as URL)
do {
    // Perform the request
    var response: AutoreleasingUnsafeMutablePointer<URLResponse?>? = nil
    let data = try NSURLConnection.sendSynchronousRequest(request, returning: response)

I get totally lost on the part with:

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

Where do you read to learn when to use things such as URLRequest, or how or when to put url: in front of it. Even though this is just one example, I notice in building a swift application you guys use things such as NSUrl, NSObject, URLRequest. And in the documentation I have not learned about these things. And I don't understand how you guys know when to put question marks "?", or how you format it your functions like the example above.

If I am not asking this correctly, I can always explain more.

If you know what I can search for online so I can know what I am trying to learn, that would be helpful. Or a book that teaches you about UIWindows, and basic functions using stuff like NSObject and UIWindows that would be helpful.

What is difficult is understanding the API documentation. If you can't understand the api documentation, and syntax. How can you ever learn. I guess its easier, to learn by example sometimes.

解决方案

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:

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.

"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.

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.

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!

这篇关于Swift 语法,理解语言的某些部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 20:28