• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Simple Swift question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Simple Swift question


  • Subject: Re: Simple Swift question
  • From: Greg Parker <email@hidden>
  • Date: Mon, 29 Jun 2015 15:43:24 -0700

> On Jun 29, 2015, at 3:18 PM, Rick Mann <email@hidden> wrote:
>
> How are you supposed to do simple things like this, succinctly?
>
>    let url = NSURL(string: "<some url>")
>    let req = NSURLRequest(URL: url)
>    self.webView.loadRequest(req)
>
> This, obviously, doesn't work, since the results are optionals, and so need to be unwrapped. But it gets rapidly ridiculous with a bunch of nested if-lets (imagine you had more than just two operations to get from here to there). What's the right way to do this?

If you "know" that the call cannot actually fail (for example, NSURL(string:) with a valid hardcoded URL) then you can simply force-unwrap. If you are wrong then the program will halt at runtime.
    let url = NSURL(string: "<some url>")!

If you are using Swift 2.0, you can use the new `guard let` to get optional checking without the cascade of indentation.
    guard let url = NSURL(string: "<some url>")
    else { /* handle failure and either halt or return */ }
    // URL is now in scope and non-optional.
    let req = NSURLRequest(URL: url)


> Oh, I think I figured it out. NSURL(string:) is optional, but NSURLRequest(URL:) can't. Very unexpected, and the error message I was getting did not clue me in.

You can often improve diagnostics by adding the explicit types that you expect each variable to have. That can help pinpoint the place where your understanding of the code and the compiler's understanding of the code don't match.

For example, in your code above, writing `let url: NSURL = …` moves the error message from the NSURLRequest line to the NSURL line.


--
Greg Parker     email@hidden     Runtime Wrangler



_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden


  • Follow-Ups:
    • Re: Simple Swift question
      • From: Rick Mann <email@hidden>
References: 
 >Simple Swift question (From: Rick Mann <email@hidden>)

  • Prev by Date: Re: Simple Swift question
  • Next by Date: Re: Simple Swift question
  • Previous by thread: Re: Simple Swift question
  • Next by thread: Re: Simple Swift question
  • Index(es):
    • Date
    • Thread