<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Coding Explorer Blog</title>
	<atom:link href="https://www.codingexplorer.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codingexplorer.com/</link>
	<description>Exploring how to code for iOS in Swift and Objective-C</description>
	<lastBuildDate>Tue, 23 May 2023 08:03:27 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Error Handling in Swift</title>
		<link>https://www.codingexplorer.com/error-handling-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 05 May 2016 13:01:30 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1188</guid>

					<description><![CDATA[<p>Ideally, errors should never occur.  File we need should always be available and networks should always be present and reliable.  Unfortunately this reality is not ideal and we have to deal with the consequences.  Thankfully the Swift team included a great way to handle these deviations from the ideal in Swift 2.  Swift Error Handling [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/error-handling-swift/">Error Handling in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="600" height="300" src="https://www.codingexplorer.com/wp-content/uploads/2016/05/ErrorHandlingInSwiftTitle.png" class="rss-featured-image wp-post-image" alt="Error Handling In Swift" align="" style="display:block;margin:10px auto;" decoding="async" fetchpriority="high" srcset="https://www.codingexplorer.com/wp-content/uploads/2016/05/ErrorHandlingInSwiftTitle.png 600w, https://www.codingexplorer.com/wp-content/uploads/2016/05/ErrorHandlingInSwiftTitle-300x150.png 300w" sizes="(max-width: 600px) 100vw, 600px" /><p>Ideally, errors should never occur.  File we need should always be available and networks should always be present and reliable.  Unfortunately this reality is not ideal and we have to deal with the consequences.  Thankfully the Swift team included a great way to handle these deviations from the ideal in Swift 2.  Swift Error Handling lets us quickly and easily warn the compiler whether a function can throw an error, actually throw it, and handle it in whatever way seems appropriate.<br />
<span id="more-1188"></span><br />
There is one major difference between how Objective-C handles errors, and the new Swift Error Handling.  If you done any work with NSError in Objective-C, be honest, have you ever given &#8220;nil&#8221; instead of an NSError pointer when you dealt with a method that could throw an error?  Yeah, I thought so.  In Objective-C, to PROPERLY deal with errors, you would have to do something like this:</p>
<pre class="lang:objc decode:true">NSError *err = nil;
NSString *fileStuff = [[NSString alloc] initWithContentsOfFile:@"someFile.txt" encoding:NSUTF8StringEncoding error:&amp;err];</pre>
<p>What this does is create an empty NSError object, which you then pass into that initializer with the ampersand ( &amp; ) character, which is an operator to tell it to pass its memory address.  Then, if there is an error, the called function or initializer would then find the spot in memory referred to by that address, place the appropriate NSError in it, and return from the function.  This was a way to have multiple values returned from a function, by leaving an address where the new value could be placed.  It was carried over to Swift as the &#8220;inout&#8221; keyword in a function prototype.</p>
<p>Now, if there was an error, you could look into that &#8220;err&#8221; variable and see which one it was and deal with it appropriately.  But, if you didn&#8217;t care about the errors, you could just pass in the value &#8220;nil&#8221; directly, instead of the error pointer (the &amp;err), and then any NSError thrown was just dropped into the oblivion that is nil.</p>
<p>In Swift with its new error handling syntax, dealing with errors is very explicit.  Functions make it really obvious that they can throw an error, and your program must acknowledge such, and deal with it appropriately (or very explicitly ignore it).</p>
<h2>Creating a Swift Error</h2>
<p>How&#8217;s that for a weird title, actually creating an error?  Well, actually we are creating an entity that will represent what error actually occurred in the program.  Let&#8217;s say this app needs to read from a file, but there are a few different things that could happen when it tries.  Everything could work fine, of course, or the file might not even exist.  If it exists, the user might not have sufficient permissions to read it, or the file could have been damaged or corrupted somehow.  For a function that will read this file, let&#8217;s create a Swift Error to represent those options:</p>
<pre class="lang:swift decode:true">enum FileReadingError: Error {
    case FileNotFound
    case InsufficientPermission
    case FileCorrupted
}</pre>
<p>The easiest way to create a Swift Error is to create an enumeration that conforms to the ErrorType protocol, as shown above.  Then, you make cases to represent the different error conditions.  Technically anything can conform to the ErrorType protocol, so you COULD use a struct or a class, but I personally can&#8217;t think of a very good reason to.  The enum cases are a PERFECT way to represent a limited number of possible errors by name.  They are made even better with the ability to have associated values, such as having the InsufficientPermission showing what permission level the current user is.  If you want to read more about enumerations, check out the post <a href="http://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a>.</p>
<p>Now, let&#8217;s create a function that can throw this error:</p>
<pre class="lang:swift decode:true">func pretendToReadTestFile() throws -&gt; Data {
    throw FileReadingError.FileNotFound
}</pre>
<p>Okay, this doesn&#8217;t ACTUALLY return anything and automatically throws the error, but we&#8217;re just looking at the mechanics of how to do it, not actually write a function to read a file and return its data.</p>
<p>Firstly, you have to mark the method as able to throw an error.  That is simply done by using the &#8220;throws&#8221; keyword after the arguments, but before the arrow &#8221; -&gt; &#8221; used to denote the return type.  Then, inside the function, to throw the error, you simply type &#8220;throw&#8221; and the enumeration case that you want to send as the error.  That&#8217;s it!</p>
<p>To actually call a function that throws, all you need to do is type the keyword &#8220;try&#8221; before the function call:</p>
<pre class="lang:swift decode:true">let data = try pretendToReadTestFile()</pre>
<h2>Handling Swift Errors</h2>
<p>There are 4 main ways to handle Swift Errors:</p>
<h3>Make Someone Else Do It</h3>
<p>The first way is to not handle it at all and make someone else do it.  For this one, you mark that your method that calls the throwing function itself is a throwing function.  Then, whatever calls this new function will have to handle it.  Eventually SOMETHING has to handle the error properly, but not necessarily that which calls the throwing function.  For instance, if we had a File Management object that handles multiple aspects of file management like reading and writing, we might just want to punt that error up to whoever called the file manager to instead of handling it there.</p>
<p>To do this, just mark the calling function with the &#8220;throws&#8221; keyword.  You still have to mark the function call to the actual function that might throw an error with try.  If you want to store the return from a throwing function, you just call the function and store its data like normal, but you place the &#8220;try&#8221; between the equals sign and the function call.</p>
<pre class="lang:swift decode:true">func getDataFromSomething() throws -&gt; Data {
    
    let data = try pretendToReadTestFile()
    
    return data
}</pre>
<h3>Handle Specific Swift Errors</h3>
<p>This way will probably look the most familiar to those that use exception handling in other languages.  Swift Error handling is significantly different from exception handling though, and much more faster.  Throwing a Swift Error is more like an alternative return statement, at least as far as how we use it:  Instead of returning the intended value from a function call, it returns the appropriate Swift Error.</p>
<p>Basically you wrap the call to the throwing function in a &#8220;do&#8221; statement.  Then after that you make &#8220;catch&#8221; statements, kind of like a Switch&#8217;s &#8220;case&#8221; statement, or an else-if for an if-statement, for the Swift Errors you are interested in, like so:</p>
<pre class="lang:swift decode:true">do {
    let someData = try pretendToReadTestFile()
} catch FileReadingError.FileNotFound {
    print("The file was not found.")
}</pre>
<p>All the &#8220;do&#8221; block does is contain the code that calls the throwing function and diverts it to the appropriate catch statement if an error is thrown, VERY much like a switch statement and its cases.  Also, you might not know of all of the possible errors that can be thrown, so we also have something equivalent to the &#8220;default&#8221; case in the Switch statement, or the &#8220;else&#8221; in an if-statement, which is just &#8220;catch&#8221; without a specific Swift Error mentioned:</p>
<pre class="lang:swift decode:true">do {
    let someData = try pretendToReadTestFile()
} catch {
    print("Something weird happened.")
}</pre>
<h3>Make throwing function&#8217;s return Optional</h3>
<p>If you don&#8217;t care what the error is, but just need to know either the returned value, or to know that there IS no value to return, that sounds<br />
like a job for Swift Optionals.  This way, even if the return type isn&#8217;t optional, you basically tell the compiler &#8220;If there was an error, I don&#8217;t care what it is, just set the value to nil&#8221;.  You call this with a question mark after the &#8220;try&#8221; keyword like this:</p>
<pre class="lang:swift decode:true">let possibleData = try? pretendToReadTestFile()
//possibleData now contains "nil"</pre>
<p>It is up to you when to handle specific errors with the do-catch statement or to use this style.  If you really don&#8217;t need the reason, or the reason is rather obvious, using &#8220;try?&#8221; might just be the right tool.  If you are making a network call, does it really matter to the user of your app if there was an  error for a bad URL, a lost connection, or the host wasn&#8217;t found?  It might, but for some apps it might not, all 3 of those mean you don&#8217;t have data you were trying to get, and &#8220;nil&#8221; may suffice to tell your code what to do since it doesn&#8217;t have the data it was requesting.</p>
<h3>Assure the compiler it won&#8217;t throw an Error</h3>
<p>If there&#8217;s a version with a question mark, you can bet there&#8217;s a version with an exclamation point.  If you use &#8220;try!&#8221;, much like forced unwrapping of an optional, you call the throwing function, and if it DOES throw, your app will crash.  If you are POSITIVE the call won&#8217;t throw, you can use this one.  Apple&#8217;s iBook suggests one reason may be when using a throwing function to read a file contained in your apps bundle.  Since it comes with the app, it will always be there, so you should never see a &#8220;File Not Found&#8221; or similar error.  If you do, well, there are probably bigger problems to worry about.</p>
<p>In the case of our function that always throws an error, using this will cause a crash of course, but for an example of how to use it (and to see what the crash looks like):</p>
<pre class="lang:swift decode:true">let definitelyNoData = try! pretendToReadTestFile()
//error: 'try!' expression unexpectedly raised an error: FileReadingError.FileNotFound</pre>
<h2>Conclusion</h2>
<p>I am quite happy with how the Swift Team implemented error handling in Swift.  It is a rather familiar way to handle it on the surface, but under the hood it is much faster, and less destructive than its cousin &#8220;Exception Handling&#8221;.  No jumping up the call stack, just a different return telling us the nature of an error.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftErrorHandling">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/error-handling-swift/">Error Handling in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Creating and Modifying a URL in your Swift App</title>
		<link>https://www.codingexplorer.com/creating-and-modifying-nsurl-in-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 17 Mar 2016 20:36:19 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1256</guid>

					<description><![CDATA[<p>In many types of apps, you have to access files.  They can be in your app bundle, on the file system, or even somewhere on the web.  You need to have someway to refer to where they are in your code.  On Apple platforms, you basically have 2 choices, as a String or aURL. Given [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/creating-and-modifying-nsurl-in-swift/">Creating and Modifying a URL in your Swift App</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In many types of apps, you have to access files.  They can be in your app bundle, on the file system, or even somewhere on the web.  You need to have someway to refer to where they are in your code.  On Apple platforms, you basically have 2 choices, as a String or aURL.</p>
<p>Given the address bar right above you, or any use of a terminal, a Swift String would be a very understandable choice, I mean, that&#8217;s all that text is in the address bar, right?  Many of the older APIs in the Cocoa and Cocoa Touch SDKs take URLs and Strings (referred to as a &#8220;path&#8221; in those APIs usually), but things are moving more and more towards just using URL objects everywhere.  URL objects have many advantages over String paths, most notably that you can access different parts of the URL from properties, instead of having to write your own code to parse those components from the path String.</p>
<p>Stay tuned as we learn a thing or two about creating and using URL objects in your Swift app.<br />
<span id="more-1256"></span></p>
<h2>Creating a URL in Swift</h2>
<p>There are several initializers and factory methods to create a URL in Swift, but I&#8217;m going to cover some of the more useful ones.</p>
<h3>init?(string URLString: String)</h3>
<p>This one is the most plain, and probably the most used.  This takes your Swift String version of a URL, and changes it into a URL object.  It is a failable initializer, because not all strings can make valid URLS.  There are some characters that cannot be used in URLs, and thus are percent encoded, meaning a code that CAN be sent in a URL is used in its place.  The one I personally have seen the most is %20, the &#8220;space&#8221; character.  This initializer expects only valid characters, it will not percent encode for you.  If the string does have characters or anything that can&#8217;t be converted into a valid URL, this initializer will return nil.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="swift">let NSHipster = URL(string: "http://nshipster.com/") //returns a valid URL
let invalidURL = URL(string: "www.example.com/This is a sentence") //Returns nil</pre>
<p>This is actually a convenience initializer which defers to the initializer below.</p>
<h3 class="p1"><span class="s1">init</span><span class="s2">?(string: </span><span class="s3">String</span><span class="s2">, relativeTo: </span><span class="s3">URL</span><span class="s2">?)</span></h3>
<p class="p1">This is the dedicated initializer.  Similar to the previous initializer, it is a failable one, and takes a similar URL Swift String, but it also takes an optional baseURL object, which is a URL object itself.  If the baseURL is nil, it just makes the URL entirely from the URL String, which is probably what the first initializer does under the hood.</p>
<pre class="lang:swift decode:true">let NSHipsterTwo = URL(string: "http://nshipster.com/", relativeTo: nil)   //Returns valid NSHipster URL
let article      = URL(string: "ios9/", relativeTo: NSHipster)             //Returns "http://nshipster.com/ios9/" URL</pre>
<h3 class="p1"><span class="s1">init</span><span class="s2">(fileURLWithPath: </span><span class="s3">String</span><span class="s2">, isDirectory: </span><span class="s3">Bool</span><span class="s2">)</span></h3>
<p class="p1">This is similar to the above initializer, but is meant to point at a local file or directory.  I&#8217;m not certain why there is a special version for local files, but I presume some optimizations are made (at least to start it with the file scheme, as opposed to http, or other ones).  There is a version without the isDirectory parameter, but the header file suggests using this one if you do know whether it is a directory or not.  Presumably, the other one will need to perform the check itself, while this one has you providing the answer, saving it from having to check.</p>
<h3 class="p1"><span class="s1">init</span><span class="s2">(fileURLWithPath: </span><span class="s3">String</span><span class="s2">, isDirectory: </span><span class="s3">Bool</span><span class="s2">, relativeTo: </span><span class="s3">URL</span><span class="s2">?)</span></h3>
<p class="p1">Newly added in iOS 9, this is similar to the previous one, but with the relativeToURL parameter.  Like the previous initializers, this will return a URL object that appends the path to the baseURL.  This could be used, if you had a directory of several files, where you were iterating through them to use for something.  You could supply the directory the files were in as the baseURL, and then just create the URLs with the file name as the Swift String path.</p>
<h2 class="p1">Converting URL back to a Swift String</h2>
<p class="p1">Sometimes, especially when dealing with older API, or when showing it to the user, you need to convert a URL object back to a Swift String.  Thankfully, URL provides a simple read-only property to get that out:  absoluteString.  Just call that property on your URL object and you&#8217;ve got it:</p>
<pre class="lang:swift decode:true">let articleString = article?.absoluteString
//ArticleString now contains: "http://nshipster.com/ios9/"</pre>
<p class="p1">In this case it took our article constant that we defined using the relativeToURL version of the initializer, resolved it into a complete URL from scheme until the end (which in this case is a path).  If we did have file extensions, queries, and fragments on this URL, it would resolve them as well.  The original article object was returned from the failable initializer, so that is why we still have that question mark there for Swift&#8217;s optional chaining.</p>
<h2 class="p1">Modifying a URL Object</h2>
<p class="p1">Each of these functions return a new URL object based on the one it was called from, but with the requested modification done.  They do NOT change the URL they are called from though, it remains the same.</p>
<h3 class="p1"><span class="s1">func</span><span class="s2"> appendingPathComponent(</span><span class="s3">String</span><span class="s2">, isDirectory: </span><span class="s3">Bool</span><span class="s2">) -&gt; </span><span class="s3">URL</span></h3>
<p class="p1">This one adds more path components to the URL, say if you were adding a file to the directory you&#8217;re in (which is stored in the URL this is called from).  There is a version without the isDirectory parameter like some of the initializers, but if you know whether it is a directory or not, it is recommended to use this one to save the metadata check to determine whether it is a directory or not.</p>
<h3 class="p1">func deletingLastPathComponent() -&gt; URL</h3>
<p class="p1">This method will return a new URL with the last path component deleted.  This works on the path part of a URL, so other areas of the URL are unaffected, like the domain.  So we can do this:</p>
<pre class="lang:swift decode:true">let articleTwo = NSHipster?.URLByAppendingPathComponent("ios9", isDirectory: true)
//articleTwo now contains "http://nshipster.com/ios9/"

let deletePathComp = articleTwo?.URLByDeletingLastPathComponent
//deletePathComp now contains "http://nshipster.com/"</pre>
<p>If there is no path information, things can get a bit weird.  For fun, I chained a few URLByDeletingLastPathComponent afterwards, and it ended up just appending &#8220;../&#8221; afterwards, analogous to going up a directory in the command line (cd ..).</p>
<p>There are several more modification methods and properties, but these are probably the most commonly used.</p>
<h2>Conclusion</h2>
<p>If you are curious about specifics of URL formatting specifications, you can checkout the RFC documents that Apple&#8217;s URL Class Reference mentions in how it handles URLs.  The strings used when initializing URLs must conform to <a href="https://tools.ietf.org/html/rfc2396">RFC 2396</a>, and the URLs themselves are parsed according to <a href="https://tools.ietf.org/html/rfc1738">RFC 1738</a> and <a href="https://tools.ietf.org/html/rfc1808">RFC 1808</a>.  The are pretty long but probably have anything you would want to know about URLs, URIs, etc.</p>
<p>There are many other properties in URL if you want a fully resolved URL, the baseURL, host, query, fragment, etc, and you can check them out in Apple&#8217;s URL Class Reference, but I personally primarily use absoluteString, and occasionally pathExtension.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://developer.apple.com/documentation/foundation/url">URL Class Reference &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/creating-and-modifying-nsurl-in-swift/">Creating and Modifying a URL in your Swift App</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Watch Connectivity in Swift — Application Context</title>
		<link>https://www.codingexplorer.com/watch-connectivity-swift-application-context/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 16 Feb 2016 20:43:42 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1213</guid>

					<description><![CDATA[<p>In the age of watchOS 1, the watchKit extension was on the paired iOS device, making sharing data between it and the main iOS app easy.  For the simplest of data, like preferences, we could just use NSUserDefaults with App Groups functionality.  We still should use that when sharing data between other extensions that still [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/watch-connectivity-swift-application-context/">Watch Connectivity in Swift — Application Context</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="600" height="300" src="https://www.codingexplorer.com/wp-content/uploads/2016/02/Watch-Connectivity-Application-Context.png" class="rss-featured-image wp-post-image" alt="Watch Connectivity Application Context" align="" style="display:block;margin:10px auto;" decoding="async" srcset="https://www.codingexplorer.com/wp-content/uploads/2016/02/Watch-Connectivity-Application-Context.png 600w, https://www.codingexplorer.com/wp-content/uploads/2016/02/Watch-Connectivity-Application-Context-300x150.png 300w" sizes="(max-width: 600px) 100vw, 600px" /><p>In the age of watchOS 1, the watchKit extension was on the paired iOS device, making sharing data between it and the main iOS app easy.  For the simplest of data, like preferences, we could just use NSUserDefaults with App Groups functionality.  We still should use that when sharing data between other extensions that still remain on the phone, like today view extensions, but not for watchOS apps anymore.</p>
<p>Luckily, Apple gave us a new API to use, that is significantly more robust than piggy-backing on App Groups, Watch Connectivity.  Watch Connectivity gives a lot more information about the status of the connection between your Apple Watch and its paired iPhone.  It also allows interactive messaging between the iOS App and the watchOS app, as well as background transfers that come in 3 flavors.  Those flavors are:</p>
<ol>
<li>Application Context</li>
<li>User Info Transfer</li>
<li>File Transfer</li>
</ol>
<p>Today we will be talking about the first one, Application Context.<br />
<span id="more-1213"></span></p>
<h2>What is Application Context</h2>
<p>Say you have a Watch App that has some settings that can be set from the iOS app side, like whether temperature should be shown in Celsius or Fahrenheit.  For settings like this, unless you expect the user to use the watchOS app immediately after doing this setting, sending the settings values over to the watch via a background transfer would make sense.</p>
<p>It probably isn&#8217;t IMMEDIATELY necessary, so the system might as well send it over when it would save the most battery.  You also don&#8217;t need any history, since the user probably won&#8217;t care that the setting was Celsius an hour earlier.</p>
<p>That&#8217;s where Application Context comes in.  Application Context is meant to send only the most recent data.  If you set that temperature setting from Celsius to Fahrenheit, and then set it (or another setting) to a different value before the iPhone sent the Application Context over to the Watch, it would just overwrite the previous App Context that is waiting to be sent.</p>
<p>If you did want it to have a history of previous pieces of information sent over in a way to save the most battery, that would be what the &#8220;User Info&#8221; transfer is for.  It is very similar to how you use Application Context, but it queues up the updates and sends them individually (instead of just overwriting something and only sending the most recent one).  That will be the topic of another post at some point.</p>
<h2>Setup the iOS App</h2>
<p>We&#8217;ll start with an app similar to the one made in the previous post <a href="http://www.codingexplorer.com/watchos-2-hello-world-app-in-swift/">watchOS Hello World App in Swift</a>.  However, in this one, we will add a UISwitch to the iPhone app, and update the WKInterfaceLabel on the watchOS app to say the state of the UISwitch.</p>
<p>Firstly, in the iOS app&#8217;s view controller, we need to set up a few things:</p>
<pre class="lang:swift decode:true">import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }
    func sessionDidBecomeInactive(_ session: WCSession) { }
    func sessionDidDeactivate(_ session: WCSession) { }
    
    var session: WCSession?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if WCSession.isSupported() {
            session = WCSession.default
            session?.delegate = self
            session?.activate()
        }
    }
}</pre>
<p>So, we first need to import the WatchConnectivity framework.  Without that, nothing else we do would work.  Next, to respond to callbacks from the WCSession, we need to set this ViewController as the WCSession&#8217;s delegate, and to do THAT we need it to conform to the WCSessionDelegate protocol, so add that after the ViewController&#8217;s UIViewController superclass declaration.</p>
<p>After that, we need a few methods to conform to the WCSessionDelegate.  For this app, they aren&#8217;t particularly necessary, but if would want to work with fast watch app switching, you will need to fill them out further.</p>
<p>Then, we should create a variable to contain the WCSession.  Since its source is a singleton, we don&#8217;t technically need to, but it certainly is shorter to type &#8220;session?&#8221; than &#8220;WCSession.default&#8221; every time.</p>
<p>In the earliest place to run your code, you should set up that session.  In most cases, that would be in an initializer, but since we are doing this in a ViewController, the earliest place we probably should go is viewDidLoad.  Generally though, you should not do this in a View Controller, since your app would want to be able to update its models when that specificView Controller is not loaded or onscreen.  For simplicity&#8217;s sake though, I am doing it in the ViewController just to show how to use the API.  If this View Controller is the ONLY thing that cares about using the WCSession, it would be okay, but generally that isn&#8217;t the case.</p>
<p>To set up the session, first we check the response from WCSession&#8217;s &#8220;isSupported&#8221; method.  This tells our code whether it even handles sessions.  This is particularly important if this code is run on an iPad.  You can&#8217;t currently pair an Apple Watch to an iPad, so this would respond with a false, and you should just not run any Watch Connectivity code at all.  On the iPhone though, this would respond with true.</p>
<p>Once that is checked, we will store WCSession&#8217;s defaultSession there.  After that, we will set this ViewController as the delegate, and activate the session.  This session is being used as a constant, and if we could perform the isSupported test in an initializer, we would have set it to a constant.  The session is an Optional because we don&#8217;t know if the app is being run on an iPad or not until runtime, so we will set it to the WCSession&#8217;s defaultSession if we can, or nil if not.  That way, on an iPad, when we try to access properties or methods in our session, they won&#8217;t even be run because the session is nil.</p>
<p>Put a UISwitch on your Storyboard, and wire up its Value Changed action to the ViewController code.  Inside it, we can use this code:</p>
<pre class="lang:swift decode:true">@IBAction func switchValueChanged(_ sender: UISwitch) {
    if let validSession = session {
        let iPhoneAppContext = ["switchStatus": sender.isOn]

        do {
            try validSession.updateApplicationContext(iPhoneAppContext)
        } catch {
            print("Something went wrong")
        }
    }
}</pre>
<p>First we are checking if we have a valid session, so that if this is run on an iPad, this whole code block will be skipped.  The application context is a Swift dictionary that has a Swift String as a key, and AnyObject as the payload.  These must follow the rules for property lists, and only contain certain types.  Which types you can use are covered in the previous post <a href="http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/">NSUserDefaults — A Swift Introduction</a>, because NSUserDefaults has the same limitations.  Nonetheless, we are sending a Swift Bool, which will just be mapped to the NSNumber boolean value, so that&#8217;s fine.</p>
<p>The call do updateApplicationContext can throw an error, so we have to wrap it in a do-block and &#8220;try&#8221; the call.  We&#8217;re just printing something to the console if something went wrong, but you can put whatever you need in there, like showing a UIAlertController if you need to let the user know, as well as an clean up or recovery code if it is necessary for the error.  For sending the context, that&#8217;s all we need.</p>
<h2>Set up the watchOS App</h2>
<p>We&#8217;re starting off with the app made in the previous post <a href="http://www.codingexplorer.com/watchos-2-hello-world-app-in-swift/">watchOS Hello World App in Swift</a>, so we have some setup already done.  Similar to the iPhone, we need to perform some set up to use WatchConnectivity</p>
<pre class="lang:swift decode:true">import WatchConnectivity

class InterfaceController: WKInterfaceController, WCSessionDelegate {
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }

    let session = WCSession.default

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        
        session.delegate = self
        session.activate()
    }
//...
}</pre>
<p>There&#8217;s more code in here from the previous app that is being omitted, but I&#8217;m just showing the parts associated with WatchConnectivity set up.  So again, we will import the WatchConnectivity framework, and have our Interface Controller conform to the WCSessionDelegate protocol.  Next, we will initialize the session constant to WCSession&#8217;s defaultSession singleton.</p>
<p>This is different from the iOS side, because we are setting this to a constant AND a non-optional.  We don&#8217;t need to do the same tests in the watchOS side, because clearly an Apple Watch running at least watchOS 2 supports Watch Connectivity.  Since we are initializing it right there, and there are no other platforms (like the iPad) to worry about, we don&#8217;t need it to be optional.</p>
<p>Then, rather early in your code, we&#8217;ll want to set up that session.  The awakeWithContext method is a pretty good place in an InterfaceController, so we&#8217;ll do it there.  Like the iOS app, we&#8217;ll set this class to be the delegate, and activate the session.</p>
<p>To handle actually processing the Application Context let&#8217;s made a helper method, because we might want to call it more than just when we receive a new one (you&#8217;ll see why soon).</p>
<pre class="lang:swift decode:true ">func processApplicationContext() {
    if let iPhoneContext = session.receivedApplicationContext as? [String : Bool] {

        if iPhoneContext["switchStatus"] == true {
            displayLabel.setText("Switch On")
        } else {
            displayLabel.setText("Switch Off")
        }
    }
}</pre>
<p>In relation to the Application Context, WCSession has 2 properties, applicationContext and receivedApplicationContext.  The difference is:</p>
<ul>
<li>applicationContext — The most recently <strong>SENT</strong> application context from this device.</li>
<li>receivedApplicationContext — The most recently <strong>RECEIVED</strong> application context by this device.</li>
</ul>
<p>Now, seeing them both together, at least for the received, that seems obvious, but in my first foray into this (without remember everything from the WWDC Intro to Watch Connectivity Video ?), I thought that applicationContext would be updated from the most recently sent or received because I thought it would be a consistent context.  I was VERY incorrect, and it took a while to realize these are separate.  I definitely can see why they are, since we may send different data in each, like if this is from the Watch&#8217;s perspective, the applicationContext would be the Watch&#8217;s context that the iPhone would need, while the receivedApplicationContext would be the aspect&#8217;s of the iPhone&#8217;s context that the Watch would need.  Either way though, remember that these are different, and choose the one you need.</p>
<p>So in this method, we will first try to cast the [String : AnyObject] dictionary to the [String : Bool] dictionary we need.  If that succeeds, we then will set the displayLabel&#8217;s text to be &#8220;Switch On&#8221; or &#8220;Switch Off&#8221; depending on the state of that Boolean in the Swift Dictionary.</p>
<p>When we actually receive a new Application context, this Interface Controller will get a delegate callback from our WCSession object informing us to that fact, we will call this helper method from there:</p>
<pre class="lang:swift decode:true">func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    DispatchQueue.main.async() {
        self.processApplicationContext()
    }
}</pre>
<p>Now, you probably see that didReceiveApplicationContext come&#8217;s with its own copy of the context it received.  This is placed in the aforementioned receivedApplicationContext property, so we don&#8217;t need it when we call our helper method, and that&#8217;s why it doesn&#8217;t need to take any arguments.</p>
<p>Now, what is with that dispatch_async call?  Well, these delegate callbacks are not on the Main Thread.  You should never update UI in iOS or watchOS from any thread other than the Main Thread.  Besides reading from the receivedApplicationContext, our helper method&#8217;s entire purpose is to update a UI element, so we will call that method by using dispatch_async to get back to the main thread.  The dispatch_async call takes 2 arguments, firstly the queue you want to dispatch to (which, for the main thread, we get from the dispatch_get_main_queue method), and a closure to tell it what to do, in which we just told it to call the helper method.</p>
<p>So, why are we doing this in a helper method instead of right there?  Well, didReceiveApplicationContext is called when you actually receive an new Application Context.  It is also called shortly after calling WCSession&#8217;s activateSession method if the app received a new Application Context while it was closed.  In this case though, I am using this application context as the backing store for this information.  Is that a good idea?  I&#8217;m not sure, but for a simple app like this, it made sense, because the whole point of that label is to say whether the Phone&#8217;s UISwitch was on or off.</p>
<p>So what do we do if our app is loaded and we want it to use that last received value, but there wasn&#8217;t a new one while it was closed.  We call our helper method early in our view&#8217;s lifecycle to set that label, so our awakeWithContext now looks like:</p>
<pre class="lang:swift decode:true">override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    processApplicationContext()

    session.delegate = self
    session.activate()
}</pre>
<p>Since awakeWithContext is indeed on the Main Thread, we don&#8217;t need that dispatch_async, so that is why it wasn&#8217;t in the helper method itself, and used to call the helper method from the didReceiveApplicationContext callback.</p>
<p>At the moment, the iOS App does not keep the state for this UISwitch, so keeping them in sync at startup is not as important, for a non-trivial app we would store the state of that UISwitch somewhere.  We COULD use the applicationContext property of the WCSession on the iPhone side (remember, applicationContext is the last SENT context from the device), but what if this was run on an iPad?  You could store it in NSUserDefaults, or many other places, but those are outside of the scope of how to use WatchConnectivity&#8217;s Application Context.  You can read about how to use it in the earlier post <a href="http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/">NSUserDefaults — A Swift Introduction</a> though!</p>
<h2>The Code</h2>
<p>For Completion&#8217;s sake, here is the whole code for this project:</p>
<h3>ViewController.swift</h3>
<pre class="lang:swift decode:true">import UIKit
import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }
    func sessionDidBecomeInactive(_ session: WCSession) { }
    func sessionDidDeactivate(_ session: WCSession) { }
    
    @IBOutlet var theSwitch: UISwitch!
    
    var session: WCSession?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if WCSession.isSupported() {
            session = WCSession.default
            session?.delegate = self
            session?.activate()
        }
    }
    
    func processApplicationContext() {
        if let iPhoneContext = session?.applicationContext as? [String : Bool] {
            if iPhoneContext["switchStatus"] == true {
                theSwitch.isOn = true
            } else {
                theSwitch.isOn = false
            }
        }
    }
    
    @IBAction func switchValueChanged(_ sender: UISwitch) {
        if let validSession = session {
            let iPhoneAppContext = ["switchStatus": sender.isOn]

            do {
                try validSession.updateApplicationContext(iPhoneAppContext)
            } catch {
                print("Something went wrong")
            }
        }
    }
}</pre>
<h3>InterfaceController.swift</h3>
<pre class="lang:swift decode:true">import WatchKit
import WatchConnectivity

class InterfaceController: WKInterfaceController, WCSessionDelegate {
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }

    
    @IBOutlet var displayLabel: WKInterfaceLabel!
    
    let session = WCSession.default

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        
        processApplicationContext()
        
        session.delegate = self
        session.activate()
    }
    
    @IBAction func buttonTapped() {
        //displayLabel.setText("Hello World!")
    }
    
    func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
        DispatchQueue.main.async() {
            self.processApplicationContext()
        }
    }
    
    func processApplicationContext() {
        if let iPhoneContext = session.receivedApplicationContext as? [String : Bool] {
            
            if iPhoneContext["switchStatus"] == true {
                displayLabel.setText("Switch On")
            } else {
                displayLabel.setText("Switch Off")
            }
        }
    }
}</pre>
<p>Remember, this is from the HelloWatch App, but we did not use the button on the watchOS app, so I just commented out its original capability.</p>
<h2>Conclusion</h2>
<p>And that&#8217;s how you use Watch Connectivity&#8217;s Application Context background transfer.  Going the other way (back to the phone) is done pretty much the same way, with the same delegate callbacks and properties.  Though in that case, depending on what you&#8217;re doing, you will probably want to check whether there actually is an Apple Watch paired with the device or if the Watch app is installed.</p>
<p>As I mentioned earlier, doing all of the code in your ViewController/InterfaceController may not be the best idea, but was done to simply show how the API can be used.  I am a huge fan of doing it in its own Watch Connectivity manager entity, so I highly recommend checking out Natasha The Robot&#8217;s post <a href="https://www.natashatherobot.com/watchconnectivity-say-hello-to-wcsession/">WatchConnectivity: Say Hello to WCSession</a> and it&#8217;s associated <a href="https://gist.github.com/NatashaTheRobot/6bcbe79afd7e9572edf6">GitHub Gist</a>.  These really helped me when working with Watch Connectivity.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftOperatorOverloading">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Facets of Swift, Part 5: Custom Operators — Swift Programming — Medium" href="https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc">Facets of Swift, Part 5: Custom Operators — Swift Programming — Medium</a></li>
<li><a href="http://www.kristinathai.com/watchos-2-tutorial-using-application-context-to-transfer-data-watch-connectivity-2/">watchOS 2 Tutorial: Using application context to transfer data (Watch Connectivity #2)</a> by <a href="https://twitter.com/kristinathai">Kristina Thai</a></li>
<li><a href="https://www.natashatherobot.com/watchconnectivity-application-context/">WatchConnectivity: Sharing The Latest Data via Application Context</a> by <a href="https://twitter.com/natashatherobot">Natasha The Robot</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/watch-connectivity-swift-application-context/">Watch Connectivity in Swift — Application Context</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>watchOS Hello World App in Swift</title>
		<link>https://www.codingexplorer.com/watchos-2-hello-world-app-in-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 08 Dec 2015 14:30:28 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[watchOS]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1200</guid>

					<description><![CDATA[<p>I have been working on some watchOS updates lately, and thought it would be helpful to share a bit about that.  First things first, we need to actually know how to make a watchOS app in the first place.  It&#8217;s time to do &#8220;Hello World!&#8221; watchOS style! Before we begin though, I want to help [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/watchos-2-hello-world-app-in-swift/">watchOS Hello World App in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="424" height="524" src="https://www.codingexplorer.com/wp-content/uploads/2015/12/10-HelloWorldScreen.png" class="rss-featured-image wp-post-image" alt="Hello World Screen" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/10-HelloWorldScreen.png 424w, https://www.codingexplorer.com/wp-content/uploads/2015/12/10-HelloWorldScreen-243x300.png 243w" sizes="auto, (max-width: 424px) 100vw, 424px" /><p>I have been working on some watchOS updates lately, and thought it would be helpful to share a bit about that.  First things first, we need to actually know how to make a watchOS app in the first place.  It&#8217;s time to do &#8220;Hello World!&#8221; watchOS style!</p>
<p>Before we begin though, I want to help you the reader, learn what you need to know about programming for iOS, watchOS, tvOS, or OS X in Swift.  As such, if you have any topics you would like to learn about on the Coding Explorer Blog, please suggest them to me on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a> or the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>.<br />
<span id="more-1200"></span></p>
<h2>Creating Your watchOS App</h2>
<p>Open up Xcode, and create a new project, either from the splash screen, or the menu ( File → New → Project&#8230; ).  Once there, go to the watchOS section and select Application, your screen should now look like this:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/12/01-Template.png"><img decoding="async" class="aligncenter size-full wp-image-1201" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/01-Template.png" alt="watchOS 2 Application Template" width="698" height="494" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/01-Template.png 698w, https://www.codingexplorer.com/wp-content/uploads/2015/12/01-Template-300x212.png 300w" sizes="(max-width: 698px) 100vw, 698px" /></a></p>
<p>Since it is the only option, select &#8220;iOS App with WatchKit App&#8221; and click next.  Once there, you name the app and make a few selections to set up this project.  Let&#8217;s name the app &#8220;HelloWatch&#8221;.  For this simple app, you can turn off all of the options at the bottom like the Notification Scene, Glance Scene, etc.  Those are useful, but we just want a simple &#8220;Hello World&#8221; app for this project.  Of course, make sure that your language is set to &#8220;Swift&#8221;.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/12/02-NameProject.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1202" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/02-NameProject.png" alt="Name Project Screen" width="695" height="493" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/02-NameProject.png 695w, https://www.codingexplorer.com/wp-content/uploads/2015/12/02-NameProject-300x213.png 300w" sizes="auto, (max-width: 695px) 100vw, 695px" /></a></p>
<p>For this project, the iOS app will be left blank.  If you are curious about doing a Hello World app for iOS itself, check out the post <a href="http://www.codingexplorer.com/hello-world-first-ios-app-swift/">Hello World! Your first iOS App in Swift</a>.  Select a place to save your project, and now we can get started.  Select the Interface.storyboard in &#8220;HelloWatch WatchKit App&#8221; group in the Navigator pane.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/12/03-SelectWatchKitAppStoryboard.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1203" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/03-SelectWatchKitAppStoryboard.png" alt="Select WatchKit App Storyboard" width="223" height="165" /></a></p>
<p>This is the screen for your watchOS app.  Similar to the iOS &#8220;Hello World&#8221; app, we&#8217;ll make this app have a label and a button, and tapping the button will change the text of the label.</p>
<p>So drag out a label and a button from the Object Library onto your storyboard with the label above the button:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/12/04-ObjectLibrary.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1204" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/04-ObjectLibrary.png" alt="Object Library" width="258" height="323" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/04-ObjectLibrary.png 258w, https://www.codingexplorer.com/wp-content/uploads/2015/12/04-ObjectLibrary-240x300.png 240w" sizes="auto, (max-width: 258px) 100vw, 258px" /></a></p>
<p>The label seems a bit cramped up there, so let&#8217;s make the label&#8217;s width the width of the screen by setting the Width to &#8220;Relative to Container&#8221; and giving it a value of 1.  This value describes the amount of the screen by a decimal percentage, so 1 is 100%, 0.5 is 50%, etc.  Let&#8217;s also give it a bit more room vertically, set the Height to be &#8220;Relative to Container&#8221; and give it a value of 0.25 (so 25%).  Set the text itself to &#8220;App Loaded&#8230;&#8221;, and center its alignment, if you like.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/12/05-LabelAttributes.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1205" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/05-LabelAttributes.png" alt="Label Attributes" width="257" height="547" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/05-LabelAttributes.png 257w, https://www.codingexplorer.com/wp-content/uploads/2015/12/05-LabelAttributes-141x300.png 141w" sizes="auto, (max-width: 257px) 100vw, 257px" /></a></p>
<h2>Giving Some Swift Code to Your watchOS UI</h2>
<p>That should be good for the UI.  Now let&#8217;s wire this up to some code so we can make that button do something.  The easiest way is to open up the Assistant Editor.  It is the icon with the diagonal venn-diagram in the top right:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/08r-AssistantEditor.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-837" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/08r-AssistantEditor.png" alt="Opening the Assistant Editor" width="420" height="60" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/08r-AssistantEditor.png 420w, https://www.codingexplorer.com/wp-content/uploads/2015/01/08r-AssistantEditor-300x43.png 300w" sizes="auto, (max-width: 420px) 100vw, 420px" /></a></p>
<p>To get a little more room, you can now close the Utilities pane, the button on the far right that just has a box with a bar on the right side of it.</p>
<p>Once there, either Ctrl+Drag or Right-Click-Drag from the label to somewhere in the code (by convention, usually the top of your class).  It will then ask you to name an outlet for this label.  We&#8217;ll just call it &#8220;displayLabel&#8221;.  Convention also suggests naming these (and pretty much all variables) in camel case, starting with a lowercase letter, and making the first letter of each word afterwards uppercase (so as to know when it is a new word, since we can&#8217;t use spaces in variable names).</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/12/06-LabelOutlet.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1206" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/06-LabelOutlet.png" alt="Create Label Outlet" width="334" height="165" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/06-LabelOutlet.png 334w, https://www.codingexplorer.com/wp-content/uploads/2015/12/06-LabelOutlet-300x148.png 300w" sizes="auto, (max-width: 334px) 100vw, 334px" /></a></p>
<p>Next, we will do similar for the button.  Ctrl+Drag from the button to the code (anywhere inside the class brackets is fine, I am aware of no specific convention other than below the outlets) and create an action.  Make sure that you select &#8220;action&#8221; as the type of connection.  If you create an outlet, that will let you change things about the button, like its own text, but that&#8217;s not what we want here:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/12/07-buttonAction.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1207" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/07-buttonAction.png" alt="Create Button Action" width="331" height="126" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/07-buttonAction.png 331w, https://www.codingexplorer.com/wp-content/uploads/2015/12/07-buttonAction-300x114.png 300w" sizes="auto, (max-width: 331px) 100vw, 331px" /></a></p>
<p>Again, make sure that it is an &#8220;Action&#8221;.  This will create a method named &#8220;buttonTapped&#8221; in which we shall write our code.  The code to change the WKInterfaceLabel&#8217;s text is pretty simple, it is just:</p>
<pre class="lang:swift decode:true ">@IBAction func buttonTapped() {
    displayLabel.setText("Hello World!")
}</pre>
<p>There is only 1 line in our method.  We run the &#8220;setText&#8221; method on the WKInterfaceLabel, and give it the new text as an argument.  In iOS, you can change the text in a UILabel by simply setting a property named &#8220;text&#8221;.  Currently, WatchOS does not have such a property, and we can&#8217;t even read the text back out from the label programatically.  I anticipate that will be added in a later version of watchOS, but for now, just use this method to set the text.</p>
<p>That&#8217;s pretty much it.  If you have an Apple Watch, you can connect your phone to your Mac, and install the app that way, or you can use the simulator.  In the top left, select the &#8220;HelloWatch WatchKit App&#8221; target, and whichever Phone and Watch Simulator bundle you wish (or your actual iPhone if you want to test this on real hardware).  Then simply hit the play button.  You might have to hit the &#8220;play&#8221; button a few times (especially if you don&#8217;t have SSDs in your computer, which make loading the simulators take much less time), but eventually you will be greeted with:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1208" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/09-AppLoadedScreen.png" alt="App Loaded Screen" width="424" height="524" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/09-AppLoadedScreen.png 424w, https://www.codingexplorer.com/wp-content/uploads/2015/12/09-AppLoadedScreen-243x300.png 243w" sizes="auto, (max-width: 424px) 100vw, 424px" /></p>
<p>And when you tap the button you will see:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/12/10-HelloWorldScreen.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1209" src="http://www.codingexplorer.com/wp-content/uploads/2015/12/10-HelloWorldScreen.png" alt="Hello World Screen" width="424" height="524" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/12/10-HelloWorldScreen.png 424w, https://www.codingexplorer.com/wp-content/uploads/2015/12/10-HelloWorldScreen-243x300.png 243w" sizes="auto, (max-width: 424px) 100vw, 424px" /></a></p>
<p>For completion&#8217;s sake, the entire code for the InterfaceController.swift file is:</p>
<pre class="lang:swift decode:true">import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {
    
    @IBOutlet var displayLabel: WKInterfaceLabel!

    override func awake(withContext context: Any?) {
        super.awakeWithContext(context)
        
        // Configure interface objects here.
    }
    
    @IBAction func buttonTapped() {
        displayLabel.setText("Hello World!")
    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

}</pre>
<p>With most of the code being provided by the template.</p>
<h2>Conclusion</h2>
<p><strong><strong><strong><strong>Screenshots taken from <strong>Xcode 7.1.1, code checked against version listed at top of the post.</strong></strong></strong></strong></strong></p>
<p>That&#8217;s all there is to it for a simple &#8220;Hello World!&#8221; App in watchOS.  This tutorial was intentionally left very plain.  This tutorial will be a place to refer to later so as to not repeat some of the earlier setup steps for making a watchOS app.  The later articles in this series will be more interesting, covering subjects like passing data between the iOS and watchOS app with WatchConnectivity, or how to make a complication.  Stay tuned for more watchOS and Swift tutorials!</p>
<p>Check out the next article <a href="http://www.codingexplorer.com/watch-connectivity-swift-application-context/">Watch Connectivity in Swift — Application Context</a>, to learn a bit about how to share data between your iOS and watchOS app.  It is even built upon the app from THIS article.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/watchos-2-hello-world-app-in-swift/">watchOS Hello World App in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>API Availability Checking in Swift</title>
		<link>https://www.codingexplorer.com/api-availability-checking-in-swift-2/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 13 Jul 2015 13:39:32 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1172</guid>

					<description><![CDATA[<p>With all of the new and awesome APIs that come out every year for each successive iOS version, it can be tempting to just drop support for the previous versions of iOS, and just go completely to the new stuff.  Of course though, we usually can&#8217;t do that for many reasons.  As such, we need [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/api-availability-checking-in-swift-2/">API Availability Checking in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="600" height="300" src="https://www.codingexplorer.com/wp-content/uploads/2015/07/APIAvailabilityCheckingInSwift2Title.png" class="rss-featured-image wp-post-image" alt="API Availability Checking In Swift 2" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/07/APIAvailabilityCheckingInSwift2Title.png 600w, https://www.codingexplorer.com/wp-content/uploads/2015/07/APIAvailabilityCheckingInSwift2Title-300x150.png 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /><p>With all of the new and awesome APIs that come out every year for each successive iOS version, it can be tempting to just drop support for the previous versions of iOS, and just go completely to the new stuff.  Of course though, we usually can&#8217;t do that for many reasons.  As such, we need to support older versions of iOS, and maybe dropping the oldest ones after they just become too difficult to support, or when active users on that platform drop to a certain amount.</p>
<p>There have been ways to check for API availability for some time, by checking if something responds to a selector, or just checking the iOS version ourselves and using that in a normal Swift &#8220;if&#8221; statement.  With the arrival of Swift though, we have an even nicer version of API checking, that is even helped by Xcode itself.  This allows Xcode to actually warn you if you try to use something that is unavailable on one of the deployment targets for your Swift app.<br />
<span id="more-1172"></span></p>
<h2>A Great Feature in iOS 9</h2>
<p>So, after looking at <a href="http://nshipster.com/ios9/">NSHipster&#8217;s iOS 9</a> post, I have noticed one of my favorite new additions to the APIs, NumberFormatter.Style.ordinal.  No longer do I have to make the Swift Switch statement to do this myself, and then worry about localization.  This does it ALL for me.  So Then I drop this into my code like so:</p>
<pre class="lang:swift decode:true">let nf = NumberFormatter()
nf.numberStyle = .ordinal

let output = nf.string(from: 7)
print(output)</pre>
<p>And this works great.  I run it on my en-US locale machine, and it prints out &#8220;7th&#8221; (well &#8216; Optional(&#8220;7th&#8221;) &#8216;, since stringFromNumber returns a Swift Optional String).  Of course, my machine is running iOS 9 in the simulator to do this.  What happens when I change my minimum deployment target to iOS 8?</p>
<p>In Xcode 6, if I tried something similar with an iOS 8 API trying to run on iOS 7, it would probably compile file, and then crash the iOS 7 device when I tried to run the code only available on iOS 8.  As far as it could tell, the Swift code was perfectly valid.  The symbol was available in the iOS 8 SDK, which it was building against, and didn&#8217;t particularly care about whether iOS 7 knew about it or not.</p>
<h2>Checking for API Availability</h2>
<p>In Xcode 7 and above though, now you get a build error, simply stating &#8221; &#8216;ordinal&#8217; is only available on iOS 9.0 or newer&#8221; .  Straight and to the point.  What&#8217;s even better, is that it then offers 3 fix-it options to deal with the issue of API availability.  The first one is the one that will be used probably the most, replacing it with Swift&#8217;s new &#8220;if #available&#8221; clause.  With this, you make a very readable API availability check, to see if the platform version is high enough to know about that part of the API.  You can simply select the fix-it option to add it to your code.</p>
<p>You will want to take a look at what the fix-it option does though, because in this case, what it does was incredibly accurate in checking for the version, but did unfortunately miss a finer point:</p>
<pre class="lang:swift decode:true">//This version needs some work

let nf = NumberFormatter()
if #available(iOS 9.0, *) {
    nf.numberStyle = .ordinal
} else {
    // Fallback on earlier versions
}

let output = nf.string(from: 7)
print(output)</pre>
<p>The only part that <em>REQUIRES</em> being in the if #available, is the usage of the NumberFormatter.Style.ordinal.  Everything else is available in earlier versions of iOS.  However, if the ordinal style is not set&#8230;. what is the stringFromNumber method going to do now?  It will just do the default behavior for NumberFormatter.  In this case, we&#8217;ll probably want to do something more like this:</p>
<pre class="lang:swift decode:true">let output: String?

if #available(iOS 9.0, *) {
    let nf = NumberFormatter()
    nf.numberStyle = .ordinal
    output = nf.string(from: 7)!!
} else {
    // Fallback on earlier versions
    output = myOrdinalFromNumber(7)
}

print(output ?? "nil")</pre>
<p>In this case, if we&#8217;re running under iOS 9.0 or above, the API availability check will run the first block of code and get our NumberFormatter with ordinal style working.  If not, it will call our own method that would handle writing the ordinal numbers itself for the languages we support.  I definitely understand why it performed the fix-it the way it did, it is the part that actually needed an API availability check for this deployment target.  I&#8217;m just saying to be careful because while the original fix-it would compile, it would not quite be what we wanted.</p>
<p>Within Swift&#8217;s &#8220;#available()&#8221; block, we give a comma separated list of platforms and version numbers, so if you have something that can run on iOS 7 and OSX Mavericks, the statement would look like:</p>
<pre class="lang:swift decode:true">if #available(iOS 7.0, OSX 10.9, *)</pre>
<p>Currently, the valid platform options are &#8220;iOS&#8221;, &#8220;OSX&#8221;, &#8220;watchOS&#8221;, and &#8220;<span class="s1">tvOS</span>&#8221; for use in these API availability checks.  You can leave it at any level of the <a href="http://semver.org/">semantic versioning</a> for the platform versions, so &#8220;iOS 7&#8221;, &#8220;iOS 7.1&#8221;, and &#8220;iOS 7.1.2&#8243; are all valid.</p>
<p>This API availability list must end with the asterisk &#8221; * &#8220;, basically saying that for any other platforms the if clause will be run on the minimum deployment target set in your project.  So if this was a framework, and it could work on watchOS, it will try to do so.  I&#8217;m guessing it is also there for possible future hardware.  That&#8217;s just a random guess though.</p>
<h2>Annotating Classes or Methods for API Availability</h2>
<p>Anyway, there are 2 other options that the fix-it offered to add into our Swift code: to add the &#8220;@available attribute to enclosing&#8230;&#8221; either instance method, or class, in that case, it will insert:</p>
<pre class="lang:swift decode:true ">@available(iOS 9.0, *)</pre>
<p>Either right above your instance method definition, or at the top of the class itself (depending on which one you choose).  If it&#8217;s above the instance method, then any entity in a deployment target below the specified one, like iOS 8, that tries to run this method will get the same error we saw earlier.  It basically says &#8220;This is an iOS 9 and above only method&#8221;.  In that case, the caller, under iOS 8 would need to use the &#8220;if #available&#8221;API availability check to use it or fall-back to another way to handle the situation.</p>
<p>In the other case, you mark the whole class as only available to iOS 9, so an iOS 8 app that tries to create an instance of that class will get a similar warning, thus making the user have to use the &#8220;if #available&#8221; statement there, and use some other class to handle that situation for older devices.  These definitely have their place, and probably are how Apple handles API availability under the hood themselves.</p>
<h2>Conclusion</h2>
<p>With language-level support in Swift for checking API availability, your code is even safer running on older devices.  I am particularly happy about it giving build errors to make sure that YOU KNOW whether this will run under previous platform versions or not.  The fix-its are also great additions, giving you a good starting point to letting your code take advantage of new API features, but not leaving previous versions in the dust.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://geo.itunes.apple.com/us/book/swift-programming-language/id1002622538?mt=11&amp;at=10lJ3x&amp;ct=blog-SwiftProtocolExtensions">The Swift Programming Language (Swift 2 Prerelease) &#8211; Apple Inc.</a></li>
<li><a href="http://nshipster.com/ios9/">iOS 9 — NSHipster, Nate Cook</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/api-availability-checking-in-swift-2/">API Availability Checking in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Protocol Extensions in Swift</title>
		<link>https://www.codingexplorer.com/protocol-extensions-in-swift-2/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 07 Jul 2015 16:54:54 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1165</guid>

					<description><![CDATA[<p>So, if you&#8217;re using a class, structure, or enumeration which did not provide a method that would be very helpful for your app, you could simply add it via an extension (which you can read more about in the posts Swift Extensions Part 1, and Swift Extensions Part 2).  With extensions, you can easily add methods to a [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/protocol-extensions-in-swift-2/">Protocol Extensions in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So, if you&#8217;re using a class, structure, or enumeration which did not provide a method that would be very helpful for your app, you could simply add it via an extension (which you can read more about in the posts <a href="http://www.codingexplorer.com/swift-extensions/">Swift Extensions Part 1</a>, and <a href="http://www.codingexplorer.com/swift-extensions-part-2-nested-types-subscripts-protocols/">Swift Extensions Part 2</a>).  With extensions, you can easily add methods to a type that builds upon the existing types.  One of my favorites is writing my own UIColor convenience initializer (shown in the post <a href="http://www.codingexplorer.com/create-uicolor-swift/">How to Create a UIColor in Swift</a>), that takes a value between 0 and 255, and hardcodes the alpha to 100% opacity.  I definitely understand why the authors did it the way they did, it is general so you can do many things with it, but I didn&#8217;t want the boilerplate required to convert my 0-255 based RGB values, and I CERTAINLY didn&#8217;t want to set the alpha to 100% each time when it would never be anything else in my app.</p>
<p>Well, that&#8217;s great and all for classes, structures, and enumerations&#8230;. but what about protocols?  In Swift 1, you could write your own protocol and have methods in it that would then have to be implemented by those types that adopt the protocol&#8230; but if it doesn&#8217;t have a method you need, the only thing you could do was either write an extension for each type that adopted the protocol, or write it as a global function.  That&#8217;s exactly what Apple did for a lot of functions in Swift 1, particularly many that worked with several CollectionTypes like Arrays, Dictionaries, and Sets.</p>
<p>With the coming of Swift 2 though, we now have a recourse that no longer requires global functions.  Now you CAN extend protocols with Protocol Extensions.  You can even provide default implementations for these methods defined in those protocol extensions!</p>
<p><span id="more-1165"></span></p>
<h2>Defining and Conforming to a Protocol</h2>
<p>So let&#8217;s say that we have a protocol to describe that something 2-dimensional can be moved by a certain amount, it might look something like this:</p>
<pre class="lang:swift decode:true">protocol TwoDMovable {

    mutating func relativeMove(x: Int, y: Int)
}</pre>
<p>All it has is a mutating function that will move whatever this is over in the X-axis by x amount, and in the y-axis by the y amount.  Pretty Simple.  Now let&#8217;s make something that adopts and conforms to this protocol:</p>
<pre class="lang:swift decode:true">struct myPoint: TwoDMovable {
    var x: Int
    var y: Int

    mutating func relativeMove(x: Int, y: Int) {
        self.x += x
        self.y += y
    }
}</pre>
<p>It&#8217;s just a simple point that has an X and a Y coordinate, and then gives that protocol&#8217;s function prototype an actual implementation, which just adds the amounts in the parameters to internal coordinates.</p>
<p>Simple enough.  But what if, like my UIColor extension mentioned earlier, an app used a few types that adopt this protocol, but we only ever needed to move it in the X direction.  You would have to just set the y movement to 0 each time.  While that isn&#8217;t hard, it can be annoying if you NEVER use it, and it leaves you open to making errors if you accidentally type a number there.</p>
<h2>Adding Protocol Extensions to an Existing Protocol</h2>
<p>With protocol extensions in Swift, we can just add something that moves it only in the X direction.  In this case, I am defining the positive X to be to the right, which is usually the case in iOS and Mac programming:</p>
<pre class="lang:swift decode:true">extension TwoDMovable {

    mutating func moveToTheRight(amount: Int) {
        relativeMove(x: amount, y: 0)
    }
}</pre>
<p>You make a protocol extension just like you would make an extension for any normal type, just type &#8220;extensions&#8221; and then the name of the protocol you want to make the protocol extension for.  So now we can use it like we would any other function:</p>
<pre class="lang:swift decode:true">//Make a mutable myPoint entity
var somePoint = myPoint(x: 5, y: 7)     // somePoint created at (5,7)

somePoint.moveToTheRight(amount: 4)     // somePoint now at     (9,7)</pre>
<p>Now you also see that there is a default implementation in there.  If the type implements its own version in itself or another extension, that version will be used instead of the default one here.  This one didn&#8217;t need to know anything about the internals like the names of where the X and Y values are stored, it just needed to take advantage of the moveToTheRight method that was listed in the original protocol.</p>
<h2>Adopt the Extended Protocol, Get the Protocol Extension Free</h2>
<p>So, that means if we create something else like a circle with a center and a radius like this:</p>
<pre class="lang:swift decode:true">struct myCircle: TwoDMovable {
    var centerX: Int
    var centerY: Int
    var radius: Int

    mutating func relativeMove(x: Int, y: Int) {
        centerX += x
        centerY += y
    }
}</pre>
<p>We automatically have that implementation of moveToTheRight, since myCircle implemented the relativeMove(X:Y:) method.  So the method in our protocol extension can be used the same as it was in myPoint:</p>
<pre class="lang:swift decode:true">//Make a mutable myCircle entity
var someCircle = myCircle(centerX: 2, centerY: 14, radius: 5)  //someCircle created at (2, 14)

someCircle.moveToTheRight(amount: 5)                           //someCircle now at     (7, 14)</pre>
<h2>Conclusion</h2>
<p>With the addition of protocol extensions back in Swift 2, all named types (classes, structures, enumerations, and protocols) can be extended, giving them more capability than they were originally written with.  This post has just gotten into the mechanics of creating and using protocol extensions.  Later on we&#8217;ll cover the aspects of Protocol Oriented Programming mentioned at WWDC 2015, but I&#8217;m still wrapping my mind around it like so many others.  You can watch the session about it on the Apple Developer portal (that no longer requires a login!) at <a href="https://developer.apple.com/videos/wwdc/2015/?id=408">Protocol-Oriented Programming in Swift</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://geo.itunes.apple.com/us/book/swift-programming-language/id1002622538?mt=11&amp;at=10lJ3x&amp;ct=blog-SwiftProtocolExtensions">The Swift Programming Language (Swift Prerelease) &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/protocol-extensions-in-swift-2/">Protocol Extensions in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Println Is Now Print, and Do-while Is Now Repeat-While in Swift</title>
		<link>https://www.codingexplorer.com/println-is-now-print-and-do-while-is-now-repeat-while-in-swift-2/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 25 Jun 2015 16:49:51 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1149</guid>

					<description><![CDATA[<p>There are a few differences from Swift 2 that probably don&#8217;t need their own post, but should be mentioned nonetheless because they do have significant implications.  This post will cover a few of those changes:  Print replacing Println and the Repeat-While loop replacing the Do-While loop. Print Replaces Println in Swift 2 You may have noticed [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/println-is-now-print-and-do-while-is-now-repeat-while-in-swift-2/">Println Is Now Print, and Do-while Is Now Repeat-While in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="600" height="300" src="https://www.codingexplorer.com/wp-content/uploads/2015/06/PrintAndTheRepeat-WhileLoop.png" class="rss-featured-image wp-post-image" alt="Print And The Repeat-While Loop in Swift 2" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/06/PrintAndTheRepeat-WhileLoop.png 600w, https://www.codingexplorer.com/wp-content/uploads/2015/06/PrintAndTheRepeat-WhileLoop-300x150.png 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /><p>There are a few differences from Swift 2 that probably don&#8217;t need their own post, but should be mentioned nonetheless because they do have significant implications.  This post will cover a few of those changes:  Print replacing Println and the Repeat-While loop replacing the Do-While loop.<br />
<span id="more-1149"></span></p>
<h2>Print Replaces Println in Swift 2</h2>
<p>You may have noticed a difference in the prior article <a href="http://www.codingexplorer.com/the-guard-statement-in-swift-2/">The Guard Statement in Swift</a> in some of the conditionals, though since the difference only consists of a couple characters, maybe you didn&#8217;t.  What is that change?  The Swift 1&#8217;s println function was replaced with the &#8220;print&#8221; function.  In Swift 1, println would print a line of text, with a &#8220;newline&#8221; character at the end, so each call to println would be on a new line.  If you just wanted to print a line, but not have the automatically appended &#8220;newline&#8221; character (so additional calls to the function would keep printing on the same line), you would use &#8220;print&#8221;.  Perhaps people did not use Swift 1&#8217;s &#8220;print&#8221; much?  Either way, it was decided to take that function name for the more common println call.</p>
<p>What if you wanted to use Swift 1&#8217;s original &#8220;print&#8221; in your Swift 2 code?  It&#8217;s still there, but in a longer format.  In Swift 1.2, we had:</p>
<pre class="lang:swift decode:true">//Swift 1.2 Version

print(value: T)
print(value: T, &amp;target: TargetStream)
println()
println(value: T)
println(value: T, &amp;target: TargetStream)</pre>
<p>Now, we have:</p>
<pre class="lang:swift decode:true">//Current Swift Version

print(items: Any...)
print(items: Any..., to: &amp;TextOutputStream)
print(items: Any..., separator: String, terminator: String)
print(items: Any..., separator: String, terminator: String, to: &amp;TextOutputStream)</pre>
<p>So now, 6 functions have been consolidated into effectively 4.  If you want a line that automatically ends with a newline character, you use:</p>
<pre class="lang:swift decode:true">print("Something with its own line!")</pre>
<p>While if you want it to not have the newline, you have to give it a blank string for the &#8220;terminator&#8221; property:</p>
<pre class="lang:swift decode:true">print("Something that shares ", terminator:"")
print("its line with others.", terminator:"")</pre>
<p>Actually, these are implemented as only 2 functions in the standard library, the separator and terminator have default values set to their parameters.  If you omit them, you just get the print(items: Any&#8230;) form of the function.  Autocomplete lists it as 4, basically with no defaults listed, and all defaults listed, but technically, with all permutations of this, it could be considered up to 8 functions.</p>
<p>This form of the print function actually will try to print a string representable form of whatever is put into that &#8220;Any&#8221; variadic parameter, and separate them with the separator parameter.  The default separator is apparently a &#8220;space&#8221; character, but you can put whatever you want in there, like a hyphen, forward-slash, etc.</p>
<p>The TextOutputStream option lets you print the output elsewhere.  Currently, the only option I can see in the standard library is to output it to another string, like using that other string as a buffer.  For most situations though, you will probably be using just print(value: T) or print(items: Any&#8230;, separator: String, terminator: String).</p>
<p>It may be something small, but I think that it is a significant change.  If nothing else, your tests or debugging code that use println() or print(value: T, appendNewLine: Bool) will need to be updated.</p>
<h2>The Repeat-While Loop</h2>
<p>Swift has a whole new way of looping?  Nah, this version has been around for a while (a &#8220;while&#8221;, get it?).  Apple decided to take the keyword &#8220;do&#8221; , and use it as part of their new Error Handling frame work.  This kind of leaves the classic do-while loop in a bit of a bind.  Well, they decided to rename it, not only to use it elsewhere, but to make the intention clearer.  Some while/do-while loops can be quite large.  With a while loop, that isn&#8217;t so bad, because you can tell right at the top that it is a while loop, and it will keep running until a certain condition.</p>
<p>With the original do-while loop, it is a bit less clear.  You will see a very small &#8220;do&#8221; at the top of a code block, then all of the code, and WAY at the bottom you will see the &#8220;while&#8221; conditional.  The idea behind it is basically saying, &#8220;Do {this big block of code} while (this conditional is true)&#8221;.  That makes sense, but the main point of loops is usually to repeat things.  While the semantics of that statement make sense, &#8220;do&#8221; does not really imply repetition.  Hence the replacement of the &#8220;do&#8221; keyword in the do-while loop to &#8220;repeat&#8221;.</p>
<p>Now, that sentence goes &#8220;Repeat {this big block of code} while (this conditional is true)&#8221;.  Saying repeat makes it very clear that this will be repeated while the while-statement&#8217;s conditional is true.  It is also to make it a bit more obvious, because the word &#8220;repeat&#8221; is significantly longer than &#8220;do&#8221;, thus making it also easier to see at the top of a big block of code in comparison to its predecessor.</p>
<p>Otherwise though, the Repeat-While loop is EXACTLY the same as the do-while loop prior to Swift 2, and how it is in many other languages.  It is a while loop that will always run the block of code ONCE, and then check the conditional.  This is as opposed to a normal &#8220;while&#8221; loop, which will check the conditional first, and if it does not evaluate to true, then the block of code will be skipped.</p>
<p>So, like it&#8217;s predecessor, its syntax is simply:</p>
<pre class="lang:swift decode:true">var count = 0

repeat {
    print("SWIFT 2 IS GREAT!")
    count += 1
} while count &lt;= 15</pre>
<p>Where the &#8220;count&#8221; initialization and incrementing are just to give the conditional something to look at.</p>
<h2>Conclusion</h2>
<p>These aren&#8217;t earth shattering topics, but I thought they were worth a mention, especially with the println change.  I didn&#8217;t want to just silently change all println statements to print, and just assume everybody saw it.  Of course, past articles will be updated to the new print style in time, along with any other updates to make them conform with Swift 2&#8217;s syntax.</p>
<p>Anyway, we will cover the new Error handling in another post, to see just where the &#8220;do&#8221; keyword went.  Stay tuned for that one, it&#8217;ll be a doozy, and maybe even require multiple posts.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/println-is-now-print-and-do-while-is-now-repeat-while-in-swift-2/">Println Is Now Print, and Do-while Is Now Repeat-While in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The Guard Statement in Swift</title>
		<link>https://www.codingexplorer.com/the-guard-statement-in-swift-2/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 17 Jun 2015 12:11:39 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<category><![CDATA[properties]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1132</guid>

					<description><![CDATA[<p>Often when working with Swift Optionals, we will want to perform an action if the Optional contains a value, or do something else if it does not.  This is done with Optional Binding with the &#8220;if let&#8221; syntax, which lets us test for wether it contains a value, and if it does, binds it to [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/the-guard-statement-in-swift-2/">The Guard Statement in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="600" height="300" src="https://www.codingexplorer.com/wp-content/uploads/2015/06/GuardStatementInSwift2TitleCompressed.png" class="rss-featured-image wp-post-image" alt="The Guard Statement In Swift Title" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/06/GuardStatementInSwift2TitleCompressed.png 600w, https://www.codingexplorer.com/wp-content/uploads/2015/06/GuardStatementInSwift2TitleCompressed-300x150.png 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /><p>Often when working with Swift Optionals, we will want to perform an action if the Optional contains a value, or do something else if it does not.  This is done with Optional Binding with the &#8220;if let&#8221; syntax, which lets us test for wether it contains a value, and if it does, binds it to a constant that can be used later in the if statement.  This works great for many cases, but it does put the emphasis on the positive case.  If there is a value, do this, otherwise do that.  Now if the code to run when there is a value is short, you can easily see what the &#8220;else&#8221; clause is tied to.  However, if the code to run when there is a value is long, then you might need to do some scrolling to see the associated else clause.</p>
<p>This is where the guard statement comes in handy, introduced with Swift 2.  The guard statement puts the emphasis on the error condition.  In this case, if there is no value, you can clearly see what will be done to deal with it.</p>
<p>What happens if there is a value?  The rest of the current scope continues running like normal.  Let&#8217;s go into an example of how the guard statement can be helpful.<br />
<span id="more-1132"></span></p>
<h2>The Simple Example</h2>
<p>We&#8217;ll start with a simple form just to show exactly what Swift&#8217;s guard statement is, in comparison to its &#8220;if&#8221; statement counterpart.</p>
<p>Let&#8217;s say that we have a function that takes a custom object that contains information about an iOS development blog, like the one below:</p>
<pre class="lang:swift decode:true">struct iOSDevelopmentBlog {
    let name: String?
    let URL: String?
    let Author: String?
}</pre>
<p>All of these Swift String properties are marked as optional.  For the simplest form of our example, let&#8217;s just read the name Swift String and right a response based on that.  With if-let, you could do it like this:</p>
<pre class="lang:swift decode:true">func originalStyleComplimentAboutBlog(blog: iOSDevelopmentBlog) {
    if let blogName = blog.name {
        print("The \(blogName) blog is a great iOS Development Blog!")
    } else {
        print("I don't know the name of this blog, but it's a good one!")
    }
}</pre>
<p>That seems simple enough.  Check whether the &#8220;name&#8221; property has a value, and use it in the compliment string that is printed out, otherwise, print some general statement about this blog.  To write the equivalent statement using Swift&#8217;s guard statement syntax, the code would look like this:</p>
<pre class="lang:swift decode:true">func guardStyleComplimentAboutBlog(blog: iOSDevelopmentBlog) {
    guard let blogName = blog.name else {
        print("I don't know the name of this blog, but it's a good one!")
        return
    }
    
    print("The \(blogName) blog is a great iOS Development Blog!")
}</pre>
<p>There are a few things to notice specifically about this.  As mentioned before, we are binding the blog.name property to the &#8220;blogName&#8221; constant.  However, if you are used to the if let syntax, and basically any use of Swift Optionals prior to Swift 2, you will notice something REALLY weird.  We&#8217;re using that optionally bound constant OUTSIDE of the scope of the conditional.  In an if-let style, we could only use it in the brackets after the &#8220;if&#8221; statement, in the &#8220;true&#8221; case.</p>
<p>For the guard statement, the &#8220;true&#8221; case, is the entire rest of the function.  The guard statement MUST be written with an else clause, because that&#8217;s all it is, really.  You try to optionally bind the value from a Swift Optional, and if it fails, run what is in the guard statement, otherwise, continue on.  This lets the compiler know that it is okay to leave the optionally bound constant visible in the enclosing scope, because we have verified that it is indeed a valid value.</p>
<p>Also, note that after printing the general compliment in the guard statement, we returned from the function.  Guard statements MUST transfer control away from its enclosing scope, in order to leave the scope it is written in.  In this case, it must leave the function, via the &#8220;return&#8221; keyword.</p>
<p>Now, okay, looking at this example, why use the guard statement instead of the if-let statement?  This one is even one line longer than the if-let style!  Well, this was the simple example just to show how an if-let is converted to its guard statement counterpart.  At this size, either is really fine.  It is more of personal preference as to whether you want the emphasis on the &#8220;true&#8221; or &#8220;false&#8221; condition for such a small function as this.  Now when things get a bit bigger, that&#8217;s where Swift&#8217;s guard statement can really shine.</p>
<h2>The Long Example</h2>
<p>Now we have three properties in our iOSDevelopmentBlog struct, if we start using those with the if-let syntax, to make a similar compliment function, we get something like this:</p>
<pre class="lang:swift decode:true">func originalStyleLongComplimentAboutBlog(blog: iOSDevelopmentBlog) {
    if let blogName = blog.name {
        print("The \(blogName) blog is a great iOS Development Blog!")
        
        if let blogAuthor = blog.Author {
            print("It is written by \(blogAuthor).")
            
            if let blogURL = blog.URL {
                print("Visit it at \(blogURL)")
            } else {
                print("Search for it on your favorite on your favorite search engine.")
            }
        } else {
            print("it is written by an unknown author.")
        }
    } else {
        print("I don't know the name of this blog, but it's a good one!")
    }
}</pre>
<p>Now, if you look at it carefully, and go through it, what it&#8217;s doing makes sense.  It prints a line about each property, and if any of them are nil, the following properties are not read and the function returns early.  The whole thing makes sense, and works&#8230;. but it is next to unreadable.  The positive cases are&#8230;.okay&#8230; you can see that if the name is there, it will print a line about the name, if the author is there it will print a line about the other.  But which of the else clauses go with what if statement?  You can follow the indentation to see which one&#8230;. but it is really unclear and confusing.</p>
<p>So with the following input:</p>
<pre class="lang:swift decode:true">let NSHipsterBlog = iOSDevelopmentBlog(name: "NSHipster", URL: "http://nshipster.com/", Author: "Nate Cook")</pre>
<p>We would get the following Output:</p>
<p style="padding-left: 30px;">The NSHipster blog is a great iOS Development Blog!<br />
It is written by Nate Cook.<br />
Visit it at http://nshipster.com/</p>
<p>Now let&#8217;s look at a functionally equivalent function using Swift&#8217;s guard statement:</p>
<pre class="lang:swift decode:true">func guardStyleLongComplimentAboutBlog(blog: iOSDevelopmentBlog) {
    guard let blogName = blog.name else {
        print("I don't know the name of this blog, but it's a good one!")
        return
    }
    
    print("The \(blogName) blog is a great iOS Development Blog!")
    
    guard let blogAuthor = blog.Author else {
        print("it is written by an unknown author.")
        return
    }
    
    print("It is written by \(blogAuthor).")
    
    guard let blogURL = blog.URL else {
        print("Search for it on your favorite on your favorite search engine.")
        return
    }
    
    print("Visit it at \(blogURL)")
}</pre>
<p>Firstly, besides being inside the function itself, there are NO NESTED SCOPES!  That makes things so much easier to read already.  So now, you see that if the &#8220;name&#8221; property does not contain a Swift String, it prints the general statement about the name, and then returns.  If it does find it, it prints the appropriate compliment.  Then, if the author is nil, it prints something general about the other and returns, otherwise it will continue and mention the blog author.</p>
<p>It is about the same number of lines (not counting white space) as the if-let style, but it is really easy to tell which else clause goes with what conditional.  It is almost as easy to tell which &#8220;true&#8221; case goes with which, since it comes right after the guard statement.</p>
<p>If you don&#8217;t need individual else clauses for each conditional, both the if and guard statements can benefit from the compound optional bindings brought with Swift 1.2.</p>
<p>This would result in an if-let style like this:</p>
<pre class="lang:swift decode:true">func compoundOriginalStyleLongComplimentAboutBlog(blog: iOSDevelopmentBlog) {
    if let blogName = blog.name,
       let blogURL = blog.URL,
       let blogAuthor = blog.Author{
        print("The \(blogName) blog is a great iOS Development Blog!")
        print("It is written by \(blogAuthor).")
        print("")
        print("Visit it at \(blogURL)")
    } else {
        print("My information is incomplete, but I'm sure this iOS Development Blog is great!")
    }
}</pre>
<p>Or this using the guard statement:</p>
<pre class="lang:swift decode:true">func compoundGuardStyleLongComplimentAboutBlog(blog: iOSDevelopmentBlog) {
    
    guard let blogName = blog.name,
          let blogURL = blog.URL,
          let blogAuthor = blog.Author else {
            print("My information is incomplete, but I'm sure this iOS Development Blog is great!")
            return
    }
    
    print("The \(blogName) blog is a great iOS Development Blog!")
    print("It is written by \(blogAuthor).")
    print("")
    print("Visit it at \(blogURL)")
}</pre>
<h2>A Guard Statement MUST Transfer Control</h2>
<p>Each guard statement has to end in something that will transfer control from the scope that the guard statement is in.  So for functions and methods, that would be &#8220;return&#8221;, usually.  If it is used in a loop like a for loop or while loop, you could use break, leaving it in the current function, but getting out of the loop.  In loops you could also use &#8220;continue&#8221;, which basically tells it to skip that iteration of the loop, and go to the next iteration, but remain in the loop.</p>
<p>So, if we have input and a loop like this:</p>
<pre class="lang:swift decode:true">let maybeNumbers: [Int?] = [3, 7, nil, 12, 40]

for maybeValue in maybeNumbers {
    
    guard let value = maybeValue else {
        print("No Value")
        break
    }
    
    print(value)
}</pre>
<p>The output would be:</p>
<p style="padding-left: 30px;">3<br />
7<br />
No Value</p>
<p>However, if the guard statement instead was:</p>
<pre class="lang:swift decode:true">guard let value = maybeValue else {
    print("No Value")
    continue
}</pre>
<p>Where &#8220;continue&#8221; is used, we would get the output:</p>
<p style="padding-left: 30px;">3<br />
7<br />
No Value<br />
12<br />
40</p>
<p>If things have REALLY gone wrong, you can also call functions that don&#8217;t return, like Swift&#8217;s preconditionFailure() function.  Those functions must be marked with the @noreturn attribute, not just have no return value.  In Swift, a function lacking a return value, but not marked as @noreturn actually returns (), the empty tuple.</p>
<p><span style="text-decoration: underline;"><strong>The point is, the guard statement MUST get out of the block of code it currently is in.</strong></span></p>
<h2>Conclusion</h2>
<p>The guard statement was a great addition to Swift.  It cleans up code that has a lot of else clauses to go along with their if statements.  It keeps the code that deals with a broken conditional NEAR that conditional, as opposed to the end of the &#8220;true&#8221; clause of an &#8220;if&#8221; statement.  It also has access to the compound optional bindings, making it even more compact.</p>
<p>The only thing I might ask to change about it, would be if we did not have to write &#8220;return&#8221; explicitly in each guard statement, if it could infer what control transfer command to use from context if omitted (similar to how you do not need to use &#8220;break&#8221; in a Swift Switch statement (unlike their C counterparts)).  On the flip side though, having it written explicitly makes it REALLY obvious that you will not be continuing in that scope (or loop iteration) if that condition is met.  They would also have to arbitrarily choose one for the loops, either &#8220;break&#8221; or &#8220;continue&#8221;, for which there really isn&#8217;t a good default.  It would all depend on the point of that loop.  I guess doing so would sacrifice some clarity and consistency for less lines of code to write for default cases, so that&#8217;s probably why the control flow statement is written explicitly in the guard statement in Swift.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/the-guard-statement-in-swift-2/">The Guard Statement in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pattern Matching in Swift</title>
		<link>https://www.codingexplorer.com/pattern-matching-in-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 29 Apr 2015 12:31:35 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1098</guid>

					<description><![CDATA[<p>Pattern matching is a staple of functional languages.  At its core, Swift is primarily an object-oriented language, like Objective-C is.  However, there are many advantages to the way more functional style languages like Haskell and Erlang do things that the designers of Swift decided to include.  Pattern matching in particular, saves us having to type [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/pattern-matching-in-swift/">Pattern Matching in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="600" height="300" src="https://www.codingexplorer.com/wp-content/uploads/2015/04/PatternMatchingInSwift.png" class="rss-featured-image wp-post-image" alt="" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/04/PatternMatchingInSwift.png 600w, https://www.codingexplorer.com/wp-content/uploads/2015/04/PatternMatchingInSwift-300x150.png 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /><p>Pattern matching is a staple of functional languages.  At its core, Swift is primarily an object-oriented language, like Objective-C is.  However, there are many advantages to the way more functional style languages like Haskell and Erlang do things that the designers of Swift decided to include.  Pattern matching in particular, saves us having to type much longer, and less readable statements to do the same checks.</p>
<p>I mean, which is easier to read:</p>
<pre class="lang:swift decode:true ">case (_, 0, 0):</pre>
<p>or</p>
<pre class="lang:swift decode:true ">if (someTuple.1 == 0) &amp;&amp; (someTuple.2 == 0)</pre>
<p>They both will find the same thing, but one can be used in a switch statement, and the other has to dig into the internals of a tuple and write a much longer looking comparison to 0 for each.  Not to mention the logical &amp;&amp; there, to make sure both of them are true.<br />
<span id="more-1098"></span></p>
<h2>What Is a Pattern?</h2>
<p>Now, firstly, what are we even referring to as a pattern?  These don&#8217;t look like repeated decorative designs to me.  I&#8217;m still pretty new to the concept in its more abstract form here, but based on what <a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftPatternMatching-Content">Apple&#8217;s iBook “The Swift Programming Language.”</a> says:</p>
<blockquote><p>A <em>pattern</em> represents the structure of a single value or a composite value.</p></blockquote>
<p>That&#8217;s still pretty high level.  Let&#8217;s see if <a href="http://en.wikipedia.org/wiki/Pattern_matching">Wikipedia</a> can help a bit more:</p>
<blockquote><p>In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern.</p></blockquote>
<p>Okay&#8230; that&#8217;s helping me a bit.  It seems that it is more talking about finding specific sequences of characters in the code to denote something.  That&#8217;s still not a particularly great way of putting it, but for instance, as we&#8217;ve seen in the earlier post <a href="http://www.codingexplorer.com/tuples-in-swift-create-read-and-return/">Tuples in Swift: Create, Read, and Return</a>, a Tuple is constructed by having comma separated values within parentheses, like (x, y, z).  The compiler should figure out by seeing that, that it is referring to a Tuple of 3 values, that are denoted as x, y, z.</p>
<p>In Swift, Patterns are used in variable/constant declaration, switch statement cases, catch blocks, and various conditionals (if, while, guard, and for-in statements).  However, only some of these patterns can be used the declaration and for-in statements:</p>
<table border="1">
<tbody>
<tr>
<td>Pattern</td>
<td>Switch Cases</td>
<td>Conditionals</td>
<td>Declarations</td>
</tr>
<tr>
<td>Wildcard</td>
<td>X</td>
<td>X</td>
<td> X</td>
</tr>
<tr>
<td>Value-Binding</td>
<td>X</td>
<td>X</td>
<td>X</td>
</tr>
<tr>
<td>Identifier</td>
<td>X</td>
<td>X</td>
<td>X</td>
</tr>
<tr>
<td>Tuple</td>
<td>X</td>
<td>X</td>
<td>X</td>
</tr>
<tr>
<td>Enumeration Case</td>
<td>X</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Optional</td>
<td>X</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>&#8220;Is&#8221; Type-Casting</td>
<td>X</td>
<td></td>
<td></td>
</tr>
<tr>
<td>&#8220;As&#8221; Type-Casting</td>
<td>X</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Expression</td>
<td>X</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<p>Just from those names, you probably have a decent idea of what some of them are, and they may even seem familiar.  We&#8217;ve covered almost all of these to SOME extent before, but not from the perspective of being a pattern.</p>
<p>Let&#8217;s step through each of them:</p>
<h2>Wildcard Pattern</h2>
<p>This one is very simple.  This is the &#8220;Don&#8217;t care&#8221; style of pattern.  It just ignores a value, so if we wanted to check if say, a value was on the X axis, for our (x, y, z) tuple, but we don&#8217;t care what its actual value is, we could check for it with the pattern (_, 0, 0), saying that it has 0 for its y and z components, and so any x value will match.</p>
<h2>Value-Binding Pattern</h2>
<p>This is one of the patterns that sounds a lot more sophisticated than what it actually is.  This is, pretty much, referring to using &#8220;var&#8221; or &#8220;let&#8221; in order to declare a variable or a constant.  That doesn&#8217;t mean that it isn&#8217;t useful though, particularly when used in a Switch&#8217;s case statement.  There you can temporarily bind values to a variable or constant after matching it to a pattern, so a case like:</p>
<pre class="lang:swift decode:true ">case let (x, 0, 0):</pre>
<p>Would match for a value on the X axis, and then bind its X component to the constant named &#8220;x&#8221; so that it can be used in the case statement, like to print it, or perform a calculation.</p>
<h2>Identifier Pattern</h2>
<p>This one, if I understand it correctly, is even simpler than the Value-Binding Pattern.  This seems to basically be the variable name itself when binding a value with the value-binding pattern, so in the above example, the &#8220;x&#8221; is the pattern, basically saying, when you find something that is (something, 0, 0), put that something in &#8220;x&#8221;.  The reason it seems so intertwined, is because, as Apple says, the identifier pattern is a sub-pattern of the value-binding pattern.</p>
<h2>Tuple Pattern</h2>
<p>We already mentioned this somewhat, but the part that wasn&#8217;t mentioned was that a tuple isn&#8217;t just a series of comma-separated values between parenthesis, it&#8217;s actually comma-separated <strong>patterns</strong>.  As such, the identifier pattern (the &#8220;x&#8221; in the tuple), was one of the patterns it was matching to within the tuple pattern itself.</p>
<h2>Enumeration Case Pattern</h2>
<p>This appears to be exactly what it sounds like, it matches to the value of an enumeration in any conditional statement.  So if you have a cardinal direction enumeration, with the options North, South, East, and West, the enumeration case pattern is referring to how it will match to the specific enumeration value, so &#8220;case .North&#8221; will only match for the &#8220;.North&#8221; value of the enumeration.  This also extends to talking about Swift Enumerations that have associated values.  If that case does have an associated value, than a Tuple type of the number of elements associated with that Enumeration case must be appended to the enumeration case itself.  This used to just be used in Swift&#8217;s Switch statement, but in Swift 2 was broadened to all you to test for enumeration cases in pretty much any conditional (if, while, guard, and for-in).</p>
<h2>&#8220;Is&#8221; Type-Casting Pattern</h2>
<p>This refers to using the &#8220;is&#8221; operator in a switch statement&#8217;s case.  If the value being checked is a member of the type on the right side of the &#8220;is&#8221; operator, that pattern will be matched, and thus that case will execute.  So if we were stepping through an older NSArray that might have different types in it, we could check if the value we are looking at is a String with the case:</p>
<pre class="lang:swift decode:true">case is String:</pre>
<p>Then that case would be run.  We wouldn&#8217;t have the value of the String though, that&#8217;s where the next pattern comes in.</p>
<h2>&#8220;As&#8221; Type-Casting Pattern</h2>
<p>Similarly, this is using the &#8220;as&#8221; operator in a switch statement&#8217;s case.  If the value being checked is a member of the type on the right side of the operator, it will cast that value and put it into the pattern on the left side, usually a &#8220;Value-Binding&#8221; pattern.  So for our above example, we could have a case statement like this:</p>
<pre class="lang:swift decode:true">case let text as String:
    print("The text we found was:  \(text)")</pre>
<p>So if it found an object that was a string, it would cast the value to a Swift String, and then Value-bind it to the &#8220;text&#8221; identifier.</p>
<h2>Expression Pattern</h2>
<p>This one, at least to me, is <strong>less</strong> and <strong>more</strong> complicated than it sounds, simultaneously.  This refers to basically whether a Switch&#8217;s case statement matches a value (other than an enumerations available cases).  So, in our earlier example, of matching a Tuple pattern with (x, 0, 0), we know that internally, the Tuple is a comma-separated list of patterns.  We&#8217;ve already said that the &#8220;x&#8221; is a member of the identifier pattern.  The 0&#8217;s are members of the expression pattern, so the internal patterns to our Tuple there are (Identifier, expression, expression).</p>
<p>A bit more concretely, the expression pattern in Swift compares values with the &#8221; ~= &#8221; operator, and the match succeeds if that comparison results in a &#8220;true&#8221; value.  In many cases, particularly if the values compared are of the same type, it will just delegate to the more normal &#8221; == &#8221; operator to do the comparison.  You can override the &#8221; ~= &#8221; operator for your own class to customize how patterns match to your type if you wish.</p>
<p>For instance, it is actually used when checking if an Int value is within a range of Ints.  The range itself is certainly not an Integer, so we cannot just use the &#8221; == &#8221; operator.  However, one can conceptualize the idea of checking whether an Int is within the range, so we would need another comparison to perform that kind of check (which may be just a for-in loop under the hood for all I know), and that&#8217;s where the &#8221; ~= &#8221; operator comes in.  I don&#8217;t know if this operator has a name, but I&#8217;ll refer to it as the &#8220;equals-ish&#8221; operator.</p>
<h2>Conclusion</h2>
<p>Patterns in Swift are, at least to me, a strange mixture of being very powerful, simple, complex, and obvious, all at the same time.  They seem to basically be codification of some of the basics of the language, in such a way as to nail down exactly what they do for the compiler, and so that they can be used in other places that could take advantage of their capabilities, like a switch&#8217;s case statement.</p>
<p>I&#8217;m only scratching the surface of what they can do, but particularly since many of these patterns can themselves contain patterns, that&#8217;s where the real power comes in.  Combining them allows you very terse statements to express something that would normally need to be much longer, to get to a very specific combination of values.</p>
<p>I want this page to be a great place for people to come to understand what pattern matching in Swift means, so if you find any errors, or parts that were unclear, please let me know, so the article can be improved.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftPatternMatching">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Operator associativity - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Pattern_matching">Pattern matching — Wikipedia</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/pattern-matching-in-swift/">Pattern Matching in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Choosing Images with UIImagePickerController in Swift</title>
		<link>https://www.codingexplorer.com/choosing-images-with-uiimagepickercontroller-in-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 27 Apr 2015 20:35:09 +0000</pubDate>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=1085</guid>

					<description><![CDATA[<p>If your Swift iOS app needs to import a picture from the user&#8217;s device, you&#8217;ve come to the right place today. Let&#8217;s learn how to use UIImagePickerController to let the user select a photo from their device to load into your app. Setting up the Storyboard This is going to be a very simple storyboard.  It&#8217;s [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/choosing-images-with-uiimagepickercontroller-in-swift/">Choosing Images with UIImagePickerController in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="800" height="400" src="https://www.codingexplorer.com/wp-content/uploads/2015/04/UIImagePickerTitle.png" class="rss-featured-image wp-post-image" alt="" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/04/UIImagePickerTitle.png 800w, https://www.codingexplorer.com/wp-content/uploads/2015/04/UIImagePickerTitle-300x150.png 300w" sizes="auto, (max-width: 800px) 100vw, 800px" /><p>If your Swift iOS app needs to import a picture from the user&#8217;s device, you&#8217;ve come to the right place today.</p>
<p>Let&#8217;s learn how to use UIImagePickerController to let the user select a photo from their device to load into your app.<br />
<span id="more-1085"></span></p>
<h2>Setting up the Storyboard</h2>
<p>This is going to be a very simple storyboard.  It&#8217;s going to be a button, and a UIImageView (to show our loaded image).  So, start up a new &#8220;single view application&#8221; project, and let&#8217;s name it &#8220;ImagePickerTutorial&#8221;.  Of course set your project&#8217;s language to Swift!<a href="http://www.codingexplorer.com/wp-content/uploads/2015/04/01-ImagePickTutorialStoryboard.png"><img loading="lazy" decoding="async" class="aligncenter wp-image-1086 size-full" src="http://www.codingexplorer.com/wp-content/uploads/2015/04/01-ImagePickTutorialStoryboard.png" alt="Storyboard layout for the UIImagePickerController tutorial" width="608" height="643" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/04/01-ImagePickTutorialStoryboard.png 608w, https://www.codingexplorer.com/wp-content/uploads/2015/04/01-ImagePickTutorialStoryboard-284x300.png 284w" sizes="auto, (max-width: 608px) 100vw, 608px" /></a></p>
<p>Alright, open up your assistant editor and add an outlet to our image UIImageView:</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-1087 size-full" src="http://www.codingexplorer.com/wp-content/uploads/2015/04/02-ImagePickTutorial-imageViewOutlet.png" alt="This UIImageView will show the image that was picked." width="322" height="173" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/04/02-ImagePickTutorial-imageViewOutlet.png 322w, https://www.codingexplorer.com/wp-content/uploads/2015/04/02-ImagePickTutorial-imageViewOutlet-300x161.png 300w" sizes="auto, (max-width: 322px) 100vw, 322px" /></p>
<p>As well as an <strong>action</strong> to our button to load theUIImagePickerController:</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-1088 size-full" src="http://www.codingexplorer.com/wp-content/uploads/2015/04/03-ImagePickTutorial-LoadImageButtonAction.png" alt="This button will load the UIImagePickerController." width="335" height="200" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/04/03-ImagePickTutorial-LoadImageButtonAction.png 335w, https://www.codingexplorer.com/wp-content/uploads/2015/04/03-ImagePickTutorial-LoadImageButtonAction-300x179.png 300w" sizes="auto, (max-width: 335px) 100vw, 335px" /></p>
<h2>Loading the UIImagePickerController</h2>
<p>First, we&#8217;ll need an instance of UIImagePickerController.  Put it at class scope, so we don&#8217;t have to allocate an entirely new one each time the button is tapped.  We&#8217;ll also need to adopt a protocol to properly use UIImagePickerController, the aptly named UIImagePickerControllerDelegate, so make the top of your class look something like this:</p>
<pre class="lang:swift decode:true">class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    @IBOutlet var imageView: UIImageView!
    
    let imagePicker = UIImagePickerController()</pre>
<p>That&#8217;s the same IBOutlet we created earlier, but I&#8217;m used to having IBOutlets above most properties, so I put the imagePicker constant below it.  The UINavigationControllerDelegate is required when setting this as the delegate for the UIImagePickerController.</p>
<p>We need to give it a few options before actually presenting it.  First, we need to set our view controller as the delegate for the UIImagePickerController, to handle a few events.  So, make your viewDidLoad look like this:</p>
<pre class="lang:swift decode:true ">override func viewDidLoad() {
    super.viewDidLoad()

    imagePicker.delegate = self
}</pre>
<p>You just need to add that last line, just denoting that &#8220;self&#8221; (the view controller this is written in) is the delegate for the imagePicker.</p>
<p>Next, head over to that loadImageButtonTapped action we made earlier, and we&#8217;ll call up the UIImagePickerController there:</p>
<pre class="lang:swift decode:true">@IBAction func loadImageButtonTapped(_ sender: UIButton) {
    imagePicker.allowsEditing = false
    imagePicker.sourceType = .PhotoLibrary
        
    presentViewController(imagePicker, animated: true, completion: nil)
}</pre>
<p>We should set whether the imagePicker wants to allow editing, and we definitely need to set the sourceType property.  The sourceType property wants a value of the enum named UIImagePickerController.SourceType, which gives 3 options:</p>
<ul>
<li>UIImagePickerController.SourceType.photoLibrary</li>
<li>UIImagePickerController.SourceType.camera</li>
<li>UIImagePickerController.SourceType.savedPhotosAlbum</li>
</ul>
<p>What are the differences between photoLibrary and savedPhotosAlbum?  Basically, photoLibrary gives the user access to any of their photos available on the device, with albums, overall view, and camera roll.  The savedPhotosAlbum is pretty much just that, the images saved locally to your device, but no access to albums or any of the other views</p>
<p>The camera one is rather self explanatory.  It lets you have the camera as the imageSource.  We can cover this aspect later, for now, let&#8217;s just stick to the images saved locally to the user&#8217;s device.</p>
<p>Now, if you really want, you could run this app, and it will show the image picker as advertised.  However, it of course won&#8217;t do anything with the image you selected, since we haven&#8217;t actually implemented code to do anything with its response yet.</p>
<h2>Read the Image Picked from UIImagePickerController</h2>
<p>Remember how we set this as the UIImagePickerController&#8217;s delegate?  We probably should do that now, shouldn&#8217;t we?  We need to implement the method &#8220;imagePickerController:didFinishPickingMediaWithInfo:&#8221; which is called exactly when it sounds like it should be, when the user picks something.</p>
<pre class="lang:swift decode:true">// MARK: - UIImagePickerControllerDelegate Methods

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
        imageView.contentMode = .scaleAspectFit
        imageView.image = pickedImage
    }

    dismiss(animated: true, completion: nil)
}</pre>
<p>It will send the data back for us to use in that Swift Dictionary named &#8220;info&#8221;.  We have to unpack it from there with a key asking for what media information we want.  We just want the image, so that is what we ask for.  For reference, the available options of UIImagePickerController.InfoKey are:</p>
<ul>
<li style="list-style-type: none;">
<ul>
<li>mediaType</li>
<li>originalImage</li>
<li>editedImage</li>
<li>cropRect</li>
<li>mediaURL</li>
<li>referenceURL</li>
<li>mediaMetadata</li>
<li>livePhoto</li>
<li>phAsset</li>
<li>imageURL</li>
</ul>
</li>
</ul>
<p>So, if we did allow editing, we could get to that image there.  The &#8220;MediaType&#8221; one also lets you know if it is an Image or a Movie.  If you&#8217;re curious about the rest of these, take a look at <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImagePickerControllerDelegate_Protocol/index.html#//apple_ref/doc/constant_group/Editing_Information_Keys">Apple&#8217;s Documentation</a>.</p>
<p>So, we got out that part of the dictionary and optionally bound its type-casted form as a UIImage into the constant &#8220;pickedImage&#8221;.</p>
<p>The next line is not strictly-speaking necessary, but without it, the picture will come in and fill as much of the UIImageView as it can, and ignore its normal aspect ratio.  This is actually a property on UIView, which UIImageView inherits from.  The default is UIViewContentMode.ScaleToFill, hence it filling the area as much as it can.  UIViewContentMode.ScaleAspectFit will tell it to fill as much of the screen as it can, while respecting the actual aspect ratio.  Another option is UIViewContentMode.ScaleAspectFill, which also respects the Aspect Ratio, but it fills the entire view, which usually means zooming in such that the whole view is filled, and some of the image is outside of the view.  This one is similar to a way to fit widescreen movies on a 4:3 TV called <a href="http://en.wikipedia.org/wiki/Pan_and_scan">Pan and Scan</a>.</p>
<p>The next line of course just sets the image of the UIImageView to be the image we just got pack.  This is analogous to setting the text property of a UILabel to the Swift String that you want to show.</p>
<p>Finally, we dismiss the view controller that was presented modally, the UIImagePickerController.  It will dismiss without this in iOS 8, it seems, but Apple encourages dismissing it yourself.</p>
<p>On that note, there is one other method from the UIImagePickerControllerDelegate protocol that we should implement, imagePickerControllerDidCancel.  This one is called when the user taps the &#8220;Cancel&#8221; button.  You are handed back a reference to the cancelled UIImagePickerController, and inside this method you should again dismiss the UIImagePickerController that you presented.</p>
<pre class="lang:swift decode:true">func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}</pre>
<p>Now, you can run your app, use the UIImagePickerController, and have it&#8217;s results show up in the UIImageView!  There isn&#8217;t any zooming or panning yet, but this was mostly a tutorial for UIImagePickerController than the UIImageView itself.  We&#8217;ll cover that another day.</p>
<p>For reference, the entire code for this app is:</p>
<pre class="lang:swift decode:true">import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    @IBOutlet var imageView: UIImageView!
    
    let imagePicker = UIImagePickerController()
    
    @IBAction func loadImageButtonTapped(_ sender: UIButton) {
        imagePicker.allowsEditing = false
        imagePicker.sourceType = .photoLibrary
        
        present(imagePicker, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        imagePicker.delegate = self
    }

    // MARK: - UIImagePickerControllerDelegate Methods
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            imageView.contentMode = .scaleAspectFit
            imageView.image = pickedImage
        }
        
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}
</pre>
<h2>Conclusion</h2>
<p><strong><strong><strong> Screenshots taken from <strong>Xcode 6.3.1, code checked against version listed at top of the post.</strong></strong></strong></strong></p>
<p>One thing to note, this post borrowed heavily from Steve Lipton&#8217;s post  <a href="http://makeapppie.com/2014/12/04/swift-swift-using-the-uiimagepickercontroller-for-a-camera-and-photo-library/">Swift Swift: Using the UIImagePickerController for a Camera and Photo Library</a>.  It&#8217;s a great post, and I hadn&#8217;t used UIImagePickerController much before this point, so it was very helpful.  He covers significantly more topics like how to use the camera option, putting this whole thing in a Popover (which you&#8217;ll want to do if using this on an iPad), dealing with the situation of the device not having a camera (like the Simulator), and even some Auto Layout.  Definitely check out his blog over at <a href="http://makeapppie.com/">makeapppie.com</a> for other great iOS tutorials in Swift.</p>
<p>The UIImagePickerController makes it easy for your users to select photos from their device, and keeps the user experience consistent with the other apps that also use it, including Apple&#8217;s own apps.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImagePickerController_Class/">UIImagePickerController Class Reference — Apple Inc.</a></li>
<li><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImagePickerControllerDelegate_Protocol/">UIImagePickerControllerDelegate Protocol Reference — Apple Inc.</a></li>
<li><a href="http://makeapppie.com/2014/12/04/swift-swift-using-the-uiimagepickercontroller-for-a-camera-and-photo-library/">Swift Swift: Using the UIImagePickerController for a Camera and Photo Library — Steve Lipton</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/choosing-images-with-uiimagepickercontroller-in-swift/">Choosing Images with UIImagePickerController in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Integers and Numeric Literals in Swift</title>
		<link>https://www.codingexplorer.com/integers-and-numeric-literals-in-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 28 Feb 2015 16:43:33 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=900</guid>

					<description><![CDATA[<p>Numbers are the building blocks of any piece of software.  It eventually gets all the way down to our code being translated into a series of numbers that refer to specific CPU instructions and data to use with them.  We will stay well above that level in this post, but I thought it would be [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/integers-and-numeric-literals-in-swift/">Integers and Numeric Literals in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Numbers are the building blocks of any piece of software.  It eventually gets all the way down to our code being translated into a series of numbers that refer to specific CPU instructions and data to use with them.  We will stay well above that level in this post, but I thought it would be useful to share some of the special aspects of how numbers, particularly Integers, are handled in Swift.<br />
<span id="more-900"></span></p>
<h2>Integers</h2>
<p>In general, when programming in Swift, you will want to use the &#8220;<strong>Int</strong>&#8221; integer type for storing integer values.  This will be the most efficient way of storing a value for the platform the app is running on.  On a 64-bit machine, the Swift <strong>Int</strong> type will refer to a Int64 type.  On a 32-bit machine, the Swift <strong>Int</strong> type will refer to an Int32 type.  You can refer to either on either platform if you wish by directly declaring their type, but having it be the correct type for your CPU will be far more efficient.</p>
<p>If you are curious though, here are all of the available Integer types in Swift, as well as their minimum and maximum values:</p>
<table border="1">
<tbody>
<tr>
<td>Type</td>
<td>Min</td>
<td>Max</td>
</tr>
<tr>
<td>Int8</td>
<td>-128</td>
<td>127</td>
</tr>
<tr>
<td>UInt8</td>
<td> 0</td>
<td>255</td>
</tr>
<tr>
<td>Int16</td>
<td>-32,768</td>
<td>32,767</td>
</tr>
<tr>
<td>UInt16</td>
<td>0</td>
<td>65,535</td>
</tr>
<tr>
<td>Int32</td>
<td>-2,147,483,648</td>
<td>2,147,483,647</td>
</tr>
<tr>
<td>UInt32</td>
<td>0</td>
<td>4,294,967,295</td>
</tr>
<tr>
<td>Int64</td>
<td>-9,223,372,036,854,775,808</td>
<td>9,223,372,036,854,775,807</td>
</tr>
<tr>
<td>UInt64</td>
<td>0</td>
<td>18,446,744,073,709,551,615</td>
</tr>
</tbody>
</table>
<p>The &#8220;U&#8221; versions of each are obviously the unsigned version, hence why their maximum is twice as much as their signed version&#8217;s maximum.  So if you have really big numeric needs, you can get all the way up to almost 18.5 quintillion.  If you need access to these values in code, the min and max are readonly properties of these types.</p>
<p>Unless you have a good reason though, you should almost always use the basic Swift &#8220;Int&#8221; type.  Why, you may ask?  Well&#8230;</p>
<ul>
<li>The type inferred for an integer literal is a Swift &#8220;Int&#8221;.</li>
<li>Reduces the need to cast different Integers between the different types.</li>
</ul>
<h2>Why NOT to Use Specifically Sized Integers Usually</h2>
<p>Now, that might not seem all that necessary, but let&#8217;s say you made a method to calculate the total enclosed space in a square and its ilk in multiple dimensions (square, cube, hypercube, etc).  Is it a glorified exponentiation function?  Yeah, but it&#8217;s to prove a separate point.</p>
<p>Remember, this is a bad idea, this example is specifically showing why it is bad to use the specifically sized integers most of the time.</p>
<p>Well, we only live in 3 spacial dimensions and 1 temporal dimension.  Even if you subscribe to a much higher number of dimensions, they&#8217;re PROBABLY less then 127.  Actually, you can&#8217;t have negative dimensions, right?  So let&#8217;s use a UInt8 to store that parameter.  And we want this to work with as many lengths as possible, and we don&#8217;t want a negative length either, so let&#8217;s have the length be a UInt64.  Of course it has to return a number based on that calculation, so it will have to return a UInt64 as well, which leaves us with this prototype:</p>
<pre class="lang:swift decode:true">func calculatedSpace(length: UInt64, inDimensions dim: UInt8) -&gt; UInt64</pre>
<p>That&#8217;s looking pretty bad already, but wait, it&#8217;ll get worse.  Now if we just use type inference to create our source values, they will just come out as standard Swift Ints, let&#8217;s put those in:</p>
<pre class="lang:swift decode:true">let len = 89123123
let dim = 4

calculatedSpace(length: len, inDimensions: dim)
//error: cannot convert value of type 'Int' to expected argument type 'UInt64'</pre>
<p>Uh oh, I guess we have to convert it:</p>
<pre class="lang:swift decode:true">calculatedSpace(length: UInt64(len), inDimensions: dim)
//error: cannot convert value of type 'Int' to expected argument type 'UInt8'</pre>
<p>Well&#8230; hmm&#8230;</p>
<pre class="lang:swift decode:true">calculatedSpace(length: UInt64(len), inDimensions: UInt8(dim))</pre>
<p>There we go, now it compiles.  Oh, but we should make this into a String to be able to show the user right?  Let&#8217;s assume that we have a NumberFormatter already set up to show it the way we want to the user, we&#8217;ll just call it &#8220;nf&#8221; for now:</p>
<pre class="lang:swift decode:true">nf.string(for: calculatedSpace(length: UInt64(len), inDimensions: UInt8(dim)))</pre>
<p>Well&#8230; it compiles&#8230; It does make an optional String as its output because of how string(for: works, but that&#8217;s okay.  Well&#8230; that looks pretty bad&#8230; what if we ignored those &#8220;optimizations&#8221; and just used the default Swift Int type?</p>
<pre class="lang:default decode:true">nf.string(for: calculatedSpace(length: len, inDimensions: dim))</pre>
<p>Notice the lack of ANY casts?  Well, technically we weren&#8217;t casting, we were just instantiating new variables based on the required type.  Either way though, we didn&#8217;t have to do any of those.  It just worked like it should.  Are we using larger types than necessary?  Yeah, but it avoids that terrible mess of type-casting/initialization.  That&#8217;s obviously good for readability, but you don&#8217;t think you would get those initializations for free, do you?  Instead of just letting it work with the Ints, the long version had to convert 2 Ints to UInt64 and UInt8.  That might be okay for a small number of these, but if you did this with a million numbers in arrays, well, the processing time can become rather substantial.</p>
<hr />
<p>When would you actually want to use these other types?  Usually to call C functions, or to output a specific type of variable for hardware reasons (like if you had an actual widget to talk to like a Heart Rate Monitor or some other sensor).  One particularly common C function called, would be one to create a random number:</p>
<pre class="lang:swift decode:true">public func arc4random_uniform(_ __upper_bound: UInt32) -&gt; UInt32</pre>
<p>As you can see, it uses UInt32 for input and output.  So, to really use this in Swift, and not have to create UInt32s everywhere, you would have to cast, something like:</p>
<pre class="lang:swift decode:true">let range = 20  //a Swift Int

let randomNumber = Int(arc4random_uniform(UInt32(range)))</pre>
<p>If you type a numeric literal in directly, it will convert for you, otherwise, you&#8217;ll have to convert your Swift Integer &#8220;range&#8221; to a UInt32.  Then, to store it in a normal Swift Int, you have to create one from the UInt32 with the &#8220;Int&#8221; initializer.  In C, it pretty much had to use specific sizes like Int32, so it makes sense that we would have to convert the more general Swift Int to i&#8217;s more specific counterpart when calling C functions.</p>
<p>This has been replaced with the Int.random(in range: Range&lt;Int&gt;) call in modern Swift, but for a while that was the best way to get a random number in Swift.</p>
<h2>Numeric Literals in Different Bases</h2>
<p>This might not be something that will commonly be done in iOS, but I&#8217;m glad this is here for the times that it will be.  When you type a normal numeric literal into swift, with no adornments, it is interpreted as a decimal number, one with base ten.  In computer science though, there are 3 other bases that are useful in certain situations.  Binary (which is base 2), Octal (which is base 8), and Hexadecimal (which is base 16).  Binary is obviously because all computers, in the end, are binary, so it can show what the number appears to be on the lowest level, for each individual bit of a number.  A decimal number require 4 bits per digit, but it does not use all of the available numbers that 4 bits can show:</p>
<table border="1">
<tbody>
<tr>
<td>Max Digit</td>
<td>Binary</td>
</tr>
<tr>
<td>Octal (7)</td>
<td>111</td>
</tr>
<tr>
<td>Decimal (9)</td>
<td>1001</td>
</tr>
<tr>
<td>Hexadecimal (F or 16)</td>
<td>1111</td>
</tr>
</tbody>
</table>
<p>Each octal digit counts from 0 to 7.  Each decimal digit counts from 0 to 9.  Each hexadecimal digit counts from 0 to 15 (represented as the letter F).  Basically, Octal uses all possible combinations of 3 bits, and Hexadecimal uses all possible combinations of 4 bits.  I personally have barely ever used Octal outside of school, but I have used Hexadecimal often enough, especially when dealing with colors.  Swift makes it really easy to write in all 4 of these notations with numeric literals.</p>
<pre class="lang:swift decode:true">let decimalFortyTwo     = 42

let binaryFortyTwo      = 0b101010
let octalFortyTwo       = 0o52
let hexadecimalFortyTwo = 0x2A</pre>
<p>If you run this in a playground, you can see on the sidebar that each of these show their constant storing the value &#8220;42&#8221;.  To write in binary, you prefix the number in the numeric literal with &#8220;0b&#8221; (Zero and a lower-case letter &#8220;b&#8221;), then follow it with the binary number.  To write in Octal, prefix the number with &#8220;0o&#8221; (Zero and a lower-case letter O).  For hexadecimal, prefix it with &#8220;0x&#8221; (Zero and a lower-case letter &#8220;x&#8221;).  The letters for those prefixes must be lower-case.  However, for the letter components of the Hexadecimal numbers (A,B,C,D,E,F), upper and lower-case can be used.</p>
<h2>Numeric Literal Tips</h2>
<p>There are a couple other nice things added to how Swift handles numeric literals.  First, if you ever needed to write something using scientific notation, like the speed of light in Miles Per Second (roughly 186,000 miles per second, or 1.86 × 10<sup>5 </sup>), you would write it like this:</p>
<pre class="lang:swift decode:true">let speedOfLightMPS = 1.86e5</pre>
<p>In decimal numbers, that &#8220;e&#8221; character takes the place of the &#8220;× 10&#8221;, and the final value is the power it is being raised to, in this case 5.</p>
<p><a title="AlBlue’s Blog" href="http://alblue.bandlem.com/">Alex</a> points out that you can use a similar trick with hexadecimal numbers as well.  However in this case, you can&#8217;t use &#8220;e&#8221; because it is a valid number in hexadecimal (equalling 14), and it instead multiplies them by a power of two.  So instead of using &#8220;e&#8221;, you use &#8220;p&#8221;, resulting in something like this:</p>
<pre class="lang:swift decode:true">let hexadecimalWithExponent = 0x7p5
//hexadecimalWithExponent now contains the decimal 224</pre>
<p>The actual math of this (in decimal numbers) is:</p>
<ul>
<li> 7 × 2<sup>5</sup></li>
<li> 7 × 32 = 224</li>
</ul>
<p>For numbers below 10, Hexadecimal will appear the same as decimal.  If you were curious, the answer in hexadecimal is 0xE0.</p>
<p>You can use a lower-case or upper-case &#8220;e&#8221; or &#8220;p&#8221; in their respective bases, either should work.  Personally, I would stick to lower-case, because uppercase, especially in the case of &#8220;E&#8221;, looks too much like a hexadecimal number, particularly confusing since it is the character to do this in a normal decimal numeric literal.  But plenty of calculators use the upper-case so, to each their own.  Just remember:</p>
<ul>
<li>To multiple a           <strong>decimal</strong> number by a power of 10, use &#8220;<strong>e</strong>&#8220;.</li>
<li>To multiply a <strong>hexadecimal</strong> number by a power of 2,   use &#8220;<strong>p</strong>&#8220;.</li>
</ul>
<p>My favorite thing in Swift numeric literals though, is padding with underscores.  I don&#8217;t know about you, but when I see a number like 14134891584, without thousand separators, I have no idea how big that is, other than that it is significantly bigger than 100 thousand.</p>
<p>Well, using the normal en-US style of thousand separator (the comma) would look too much like we making Tuples in Swift.  That, and of course that separator is far from universal.  If using the period as a thousand separator, that would look like it is digging into different properties or methods within a numeric literal, as far as other Swift uses of the period character go.</p>
<p>So, Apple decided to go a completely different path and use the underscore to separate values.  You don&#8217;t have to use them, and when they&#8217;re used they appear to be just stripped out of the literal, but that makes 14134891584 into 14_134_891_584.  So much easier to read!  Now I know it is in the 14 billion range, before I just randomly hit keys, so I wasn&#8217;t sure how long it was.  So in code, it would just look like:</p>
<pre class="lang:swift decode:true">let bigNumber = 14_134_891_584</pre>
<p>You don&#8217;t have to use them as thousand separators, you can put them anywhere that seems to make sense, like in a Phone Number, for instance, to break it down to prefix, area code, country code, etc.  They&#8217;re just removed by the compiler anyway, so it just makes it easier on your eyes.</p>
<h2>Conclusion</h2>
<p>I have only used Xcode in the en-US locale, so if the compiler can take numeric literals in the 14.134.891.584,123 style, please let me know.  My cursory test in temporarily switching to a locale that does use that notation seems to not change Xcode.  The calculator app shows that notation, but the Playground does not seem to.</p>
<p>I am particularly glad that they added the underscores to make large numbers more readable.  It&#8217;s small, but makes it so much easier to tell what large numbers actually are.  It is only there for our benefit and is simply removed from the numeric literal when the compiler reads it.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftIntegers">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/integers-and-numeric-literals-in-swift/">Integers and Numeric Literals in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swift Set Type</title>
		<link>https://www.codingexplorer.com/swift-set-type/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 19 Feb 2015 18:43:02 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=975</guid>

					<description><![CDATA[<p>In Objective-C there were three basic types of Data Structures, NSArray, NSDictionary, and NSSet.  In Objective-C, the immutable and mutable forms were separate, so you also had NSMutableArray, NSMutableDictionary, and NSMutableSet.  Especially since it is often an interview question, I should point out that a Data Structure is simply &#8220;a particular way of organizing data [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-set-type/">Swift Set Type</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In Objective-C there were three basic types of Data Structures, NSArray, NSDictionary, and NSSet.  In Objective-C, the immutable and mutable forms were separate, so you also had NSMutableArray, NSMutableDictionary, and NSMutableSet.  Especially since it is often an interview question, I should point out that a Data Structure is simply &#8220;a particular way of organizing data in a computer so that it can be used efficiently.&#8221;  You can read that sentence and more at the Wikipedia article about <a title="Data structure - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Data_structure">Data Structures</a>.</p>
<p>In Swift we were greeted with Arrays and Dictionaries, but there was no Set to be found!  You had to go back to Objective-C&#8217;s NSSet to work with them.  You can read about the other two Data Structures back in the previous posts <a title="Arrays and their Methods in Swift" href="http://www.codingexplorer.com/arrays-swift/">Arrays and their Methods in Swift</a> and <a title="Swift Dictionary Quick Reference" href="http://www.codingexplorer.com/swift-dictionary-quick-reference/">Swift Dictionary Quick Reference</a>.  Well, thanks to Swift 1.2, Set has come to the land of Swift.<br />
<span id="more-975"></span></p>
<h2>What is a Set?</h2>
<p>What is a Set you might ask?  A set is an unordered collection of distinct objects.</p>
<p>How is that different from an array?  Well, an array is a <strong>ordered</strong> collection, firstly.  Each member of an array is at a specific index that you access through it&#8217;s subscript (the [#] next to the array, where you replace the # sign with the index you&#8217;re looking for).  Secondly, the objects at each index need not be distinct.  You can have the same object in at all of hte indexes if you really want to for some reason.</p>
<p>How is it different from a dictionary?  A dictionary is an unordered collection of values referenced by specific keys.  If you have a dictionary of people that are keyed by a String, you would call one with the subscript syntax as well, like &#8216; Person[&#8220;Johnny&#8221;] &#8216;.  So while it is unordered, like the Set is, each value in it is addressed by a specific key.</p>
<p>So if it isn&#8217;t indexed, or even addressable by a key, what would you possibly use a set for?</p>
<p>Does order matter with every collection of Objects?  Let&#8217;s say you were having a potluck dinner, and each person told the host/hostess what they were bringing.  You want people to see what foods are available, and the quantity doesn&#8217;t matter.</p>
<p>Some people have responded that they&#8217;ll bring &#8220;Salad&#8221;, &#8220;Chips&#8221;, and &#8220;Sandwiches&#8221;.  Somebody else comes along and says they also want to bring a &#8220;Salad&#8221;.  Salad&#8217;s good for you right?  Everybody should eat Salad more often!</p>
<p>So now, you have had people respond that there will be &#8220;Salad&#8221;, &#8220;Chips&#8221;, &#8220;Sandwiches&#8221;, and &#8220;Salad&#8221;.  If somebody is asking what will be available to eat at this dinner, do you really need to say &#8220;Salad&#8221; twice?  And does order matter at all?  Not really.  So a Set of what is available at this dinner is &#8220;Salad&#8221;, &#8220;Chips&#8221;, and &#8220;Sandwiches&#8221; still, even if there is more salad.</p>
<p>But an array is easy, and to make sure we don&#8217;t put in the same thing more than once we could just iterate through the array, see if that Object is there, and just not enter it right?  Well, checking for if that object is there usually means iterating over the rest of the array before finding the index that object is in, if it is in there at all.  That is part of where the Set shines.  The Set is a lot faster than an array.  The Set is most similar to the keys of a Dictionary type.  The keys of a dictionary must be unique, and you find that key-value pair (under the hood) by generating a hash of the key, and check for something at that hash.  That is effectively what the Set type does.</p>
<p>If you try to insert something that is already in the Set, it should just accept it, but not actually do anything.  So if we added &#8220;Salad&#8221; to our food set after the first three were added, we would still result in a set of 3 objects.  So you don&#8217;t need to check if the object is there (yourself) before inserting it.  You can just try anyway.</p>
<p>However, if you DID want to check if something is in there, say to limit people from bringing the same thing to this dinner, Set is particularly fast at testing whether an object is in the Set itself.  Since it doesn&#8217;t have to iterate over itself like the Array, it just checks whether there is something at that value&#8217;s hash.  If there is, it exists, if there is not, then it doesn&#8217;t.  This is similar to a Dictionary, where it will return nil if you try to get something from the Dictionary with a key that is not present in that Dictionary.</p>
<p>Anyway, enough chit chat, how do you use Sets in Swift?</p>
<h2>Swift Sets and their Methods</h2>
<p>These are most of the methods and properties available for the Set type:</p>
<table border="1">
<tbody>
<tr>
<td><strong>Title</strong></td>
<td><strong>Example</strong></td>
<td><strong>Description</strong></td>
</tr>
<tr>
<td>Initialize Set</td>
<td>Set&lt;String&gt;()</td>
<td>This initializes a completely empty Set.</td>
</tr>
<tr>
<td>Initialize Set from Array Literal</td>
<td>let abcSet = Set([&#8220;A&#8221;, &#8220;B&#8221;, &#8220;C&#8221;, &#8220;D&#8221;])</td>
<td>This creates a Set that contains the Strings of the first 4 letters of the alphabet.</td>
</tr>
<tr>
<td>Check Set Membership</td>
<td>foodSet.contains(&#8220;Sandwiches&#8221;)</td>
<td>This returns a Bool of whether foodSet already contains the Swift String &#8220;Sandwiches&#8221;.</td>
</tr>
<tr>
<td>Insert Value</td>
<td>foodSet.insert(&#8220;Salad&#8221;)</td>
<td>This will insert the Swift String &#8220;Salad&#8221; into the Set.</td>
</tr>
<tr>
<td>Remove Value</td>
<td>foodSet.remove(&#8220;Chips&#8221;)</td>
<td>This will remove a value from the array.  This will return an Optional of the Set&#8217;s type, with the value if it was there, or nil if it wasn&#8217;t.</td>
</tr>
<tr>
<td>Remove All Values</td>
<td>foodSet.removeAll()</td>
<td>This will completely empty the Set of all members.</td>
</tr>
<tr>
<td>Number of Elements</td>
<td>foodSet.count</td>
<td>Returns an Int of how many elements are in the Set.</td>
</tr>
<tr>
<td>Check if Empty</td>
<td>foodSet.isEmpty</td>
<td>Returns a Bool of true if the foodSet has no members.  It returns false if there are any members in the Set.</td>
</tr>
<tr>
<td>Check if Subset</td>
<td>entreeSet.isSubset(of: foodSet)</td>
<td>Returns true if entree set is a subset of foodSet.  That is, if all of entreeSet&#8217;s members are in foodSet.</td>
</tr>
<tr>
<td>Check if Strict Subset</td>
<td>entreeSet.isStrictSubset(of: foodSet)</td>
<td>Returns true if  entree set is a subset of foodSet, but not an exact copy.</td>
</tr>
<tr>
<td>Check if Superset</td>
<td>foodSet.isSuperset(of: entreeSet)</td>
<td>Returns true if foodSet is a superset of entreeSet.  That is, if foodSet contains all members of entreeSet.</td>
</tr>
<tr>
<td>Check if Strict Superset</td>
<td>sameFoodSet.isStrictSuperset(of: foodSet)</td>
<td>Returns true only if sameFoodSet is a superset of foodSet, but not an exact copy.</td>
</tr>
<tr>
<td>Check if no members same</td>
<td>foodSet.isDisjoint(with otherFoods)</td>
<td>Returns true if the two Sequences have no members in common.</td>
</tr>
<tr>
<td>Combine Sets</td>
<td>foodSet.union(otherFoods)</td>
<td>Returns a new Set containing the members of both foodSet and otherFoods.</td>
</tr>
<tr>
<td>Combine Sets In Place</td>
<td>otherFoods.formUnion(foodSet)</td>
<td>Mutates the otherFoods Set to add the members of foodSet to it.</td>
</tr>
<tr>
<td>Subtract One Set From Another</td>
<td>otherFoods.subtracting(entreeSet)</td>
<td>Returns a new Set with the values of entreeSet removed from otherFoods, if they were present.</td>
</tr>
<tr>
<td>Subtract One Set From Another In Place</td>
<td>otherFoods.subtract(entreeSet)</td>
<td>Mutates the otherFoods Set to subtract an values that were specified in the entreeSet (like above).</td>
</tr>
<tr>
<td>Create Set of Common Members</td>
<td>moreFoods.intersection(entreeSet)</td>
<td>Returns a new Set with the values that were in common between moreFoods and entreeSet.</td>
</tr>
<tr>
<td>Create Set of Common Members In Place</td>
<td>moreFoods.formIntersection(entreeSet)</td>
<td>Mutates the moreFoods Set to perform the intersect method above.</td>
</tr>
<tr>
<td>Create Set of Uncommon Members</td>
<td>moreFoods.symmetricDifference(dessertsSet)</td>
<td>Returns a new Set containing the values that were in either moreFoods or dessertsSet, but <strong>NOT</strong> both.</td>
</tr>
<tr>
<td>Create Set of Uncommon Members In Place</td>
<td>moreFoods.formSymmetricDifference(dessertsSet)</td>
<td>Mutates the moreFoods Set with the result of the exclusiveOr method above.</td>
</tr>
</tbody>
</table>
<p>If you look inside the Swift Set type in Swift 1.2 (and Swift 2.1 now), you will see that it actually does refer to Indexes in there.  It has to be addressable by the system somehow, but you probably should not mess with them.  I mean you technically can, but since the thing is unordered, the actual order they appear in will be&#8230; unpredictable is probably the wrong word, but not something I would rely on.</p>
<p>One thing to note, all of the methods from isSubsetOf down actually take a SequenceType value.  That is, a type that adopts the SequenceType protocol.  So actually, these should take even an Array, since Arrays m adopt the SequenceType protocol.  When making a union with an array, it adds the values stored at each index to the Swift Set.  A Dictionary technically is a SequenceType as well, but I think the type fails the Generic&#8217;s where clause, since it is composed of the key and value types.  However, if you can create a union between a set and either the keys or values of the array using the appropriate property of that dictionary for either the keys or values.</p>
<h2>Initializing a Swift Set</h2>
<p>As shown above, there are a few ways to initialize a Swift Set.  There isn&#8217;t technically a &#8220;Set Literal&#8221;, at least not that I&#8217;ve seen yet, but  you can create a Swift Set with an Array Literal.  Each of these ways to create a Swift Set are valid:</p>
<pre class="lang:swift decode:true">var someSet = Set&lt;String&gt;()
let abcSet: Set = ["A", "B", "C", "D"]
var foodSet = Set(["Salad", "Chips", "Sandwiches"])
</pre>
<p>The first one makes a completely empty mutable Swift Set.  The next makes a constant Set by explicitly typing that it will be a Set and then setting it with an array literal.  The final one makes a mutable Set using an initializer that takes a Swift Array Literal.  Notice how the last two don&#8217;t necessarily need the type of the elements of the Set stated explicitly.  You can if you wish, but doing this worked correctly.  I don&#8217;t know which way is best practice yet, but these are the ones currently available.  Maybe we&#8217;ll get a true Set literal in a future beta, but for now we can do it well enough with arrays.</p>
<h2>Adding and Removing Elements from a Swift Set</h2>
<p>The simplest way to add or remove items from a Set is with the insert or remove commands:</p>
<pre class="lang:default decode:true">foodSet.remove("Chips")  //Now contains: {"Salad", "Sandwiches"}

foodSet.insert("Soup")  //Now contains: {"Salad", "Sandwiches", "Soup"}

foodSet.removeAll()  //Now Contains 0 members</pre>
<p>As mentioned in the table, the remove method actually returns an Optional of the type stored in the Set.  It will return nil if the value you want to remove isn&#8217;t there in the first place, or it will return the value itself.  If you wanted to just remove everything of course, you can just run the method removeAll().</p>
<h2>Checking for Element Membership in Sets</h2>
<p>The count and isEmpty properties are pretty self explanatory, so we won&#8217;t really go over them in any more depth.  The rest of the methods however, are rather interesting.  The first inquires if a specific element is in the Swift Set, with a Bool return value.  The rest in this batch return Bools depending on what the relationship is between the Swift Set and another Sequence type (which is usually a Set, but as mentioned earlier, they could work with Arrays).</p>
<pre class="lang:swift decode:true">//foodSet     is {"Salad", "Chips", "Sandwiches"}
//entreeSet   is {"Salad", "Sandwiches"}
//sameFoodSet is {"Salad", "Chips", "Sandwiches"}
//otherFoods  is {"Quiche", "Donuts"}

foodSet.contains("Chips")               //returns true

entreeSet.isSubset(of: foodSet)           //returns true
sameFoodSet.isStrictSubset(of: foodSet)   //returns false

foodSet.isSuperset(of: entreeSet)         //returns true
foodSet.isStrictSuperset(of: sameFoodSet) //returns false
foodSet.isStrictSuperset(of: entreeSet)   //returns true

foodSet.isDisjoint(with: entreeSet)       //returns false
foodSet.isDisjoint(with: otherFoods)      //returns true</pre>
<p>The contains method returns true, since &#8220;Chips&#8221; is indeed a member of the foodSet.</p>
<p>Since entreeSet contains &#8220;Salad&#8221; and &#8220;Sandwiches&#8221;, it is a subset of the entire foodSet, so that returns true.  However, while sameFoodSet is a subset of foodSet by containing all of the same items, it is not a Strict subset, which basically means it must be <strong>PART</strong> of the set, not the whole thing, so it returns false.</p>
<p>The foodSet is a superset of the of the entreeSet, by containing at least everything in the entreeSet.  Like before, foodSet is not a Strict superset of sameFoodSet, since they are entirely the same.  However, foodSet does contain everything in entreeSet, and something that entree set does not (the &#8220;Chips), so the isStrictSuperSetOf returns true for that inquiry.</p>
<p>Finally, we can check if they are disjoint, basically saying if they have nothing in common.  The foodSet and entreeSet contain a few members in common, so isDisjointWith evaluates to false.  However, there is nothing in common between foodSet and otherFoods, so that one evaluates to true.</p>
<h2>Compare Sets</h2>
<p>The final batch create new Sets based on how the Swift Set and SequenceTypes being compared actually compare.</p>
<pre class="lang:swift decode:true">//foodSet     is {"Salad", "Chips", "Sandwiches"}
//otherFoods  is {"Quiche", "Donuts"}
//entreeSet   is {"Salad", "Sandwiches"}
//dessertsSet is {"Chips", "Ice Cream", "Donuts"}

let moreFoods = foodSet.union(otherFoods)
//moreFoods now contains {"Sandwiches", "Salad", "Chips", "Quiche", "Donuts"}


otherFoods.formUnion(foodSet)
//otherFoods now contains {"Sandwiches", "Quiche", "Salad", "Chips", "Donuts"}

otherFoods.subtract(entreeSet)
//otherFoods Set containing {"Quiche", "Chips", "Donuts"}

otherFoods.intersection(dessertsSet)
//Returns Set containing {"Chips", "Donuts"}

foodSet.symmetricDifference(dessertsSet)
//Returns Set containing {"Sandwiches", "Ice Cream", "Salad", "Donuts"}</pre>
<p>Each of them comes with a form&lt;noun&gt; style, which replaces the Swift Set it is called from with the result of whichever &lt;noun&gt; method is called.  Of course the Set this is called from must be a variable to use those versions.  We didn&#8217;t go over each form&lt;noun&gt; style of method, but they all work the same way.  You call them like shown above with formUnion.</p>
<p>Union does what it sounds like.  It combines the two sets.  If there were any in common, they would only be shown once in the resulting Swift Set.  So basically, we had &#8220;Salad&#8221;, &#8220;Chips&#8221;, &#8220;Sandwiches&#8221; from foodSet, and combined those with &#8220;Quiche&#8221; and &#8220;Donuts&#8221; from otherFoods, to get back a new set containing all of them: {&#8220;Donuts&#8221;, &#8220;Sandwiches&#8221;, &#8220;Salad&#8221;, &#8220;Quiche&#8221;, &#8220;Chips&#8221;}.</p>
<p>Next, we outright replaced otherFoods with the union of itself with foodSet.  After that, we requested a new Set with the result of subtracting the members of entreeSet (&#8220;Salad&#8221;, &#8220;Sandwiches&#8221;) from the newly modified otherFoods (&#8220;Chips&#8221;, &#8220;Sandwiches&#8221;, &#8220;Quiche&#8221;, &#8220;Salad&#8221;, &#8220;Donuts&#8221;) to result in a returned Set of (&#8220;Soup&#8221;, &#8220;Quiche&#8221;, &#8220;Donuts&#8221;).</p>
<p>Then we requested a set that was the intersection of otherFoods (&#8220;Chips&#8221;, &#8220;Sandwiches&#8221;, &#8220;Quiche&#8221;, &#8220;Salad&#8221;, &#8220;Donuts&#8221;) and dessertsSet (&#8220;Chips&#8221;, &#8220;Ice Cream&#8221;, &#8220;Donuts&#8221;). The only things in common between those two were &#8220;Chips&#8221; and &#8220;Donuts&#8221;, so those were the members of the returned Set.</p>
<p>SymmetricDifference then, creates a new Swift Set containing the members that are in either Set, but <strong>NOT</strong> both. So when taking the symmetricDifference of foodSet (&#8220;Salad&#8221;, &#8220;Chips&#8221;, &#8220;Sandwiches&#8221;) and dessertsSet (&#8220;Chips&#8221;, &#8220;Ice Cream&#8221;, &#8220;Donuts&#8221;), they have &#8220;Chips&#8221; in common, so that element is left out. This then results in a Set that is the combination of the remaining members (&#8220;Sandwiches&#8221;, &#8220;Ice Cream&#8221;, &#8220;Salad&#8221;, &#8220;Donuts&#8221;). This is basically an Exclusive Or operation.</p>
<h2>Conclusion</h2>
<p>A Swift Set provides fast lookup for whether a value is contained therein, especially compared with an Array.  When you need to know that an object is in a collection, need it to be unique, but don&#8217;t care about the order, the Swift Set may be just the Data Structure for you.  I have not used their Objective-C equivalent that much yet, but after learning all of this about the Swift version, I will probably be using them quite a bit more often.</p>
<p>This wasn&#8217;t explicitly necessary in the main part of the post, but I thought I should point out a bit more about Data Structures.  It sounds like a very highfalutin (huh, never actually written that word) word that you&#8217;ll need a degree in Computer Science to understand, but it really just means that, Structures to store Data in.  So that means it includes the simple container types in many programming languages like Arrays, Dictionaries, and Sets.  It also includes Queues, Stacks, Trees (like a Family Tree), and many more.  You can read a lot about a lot more of them at Wikipedia&#8217;s <a title="List of data structures - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/List_of_data_structures">List of Data Structures</a> page.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="The Swift Programming Language: Document Revision History" href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/RevisionHistory.html#//apple_ref/doc/uid/TP40014097-CH40-ID459">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Data structure - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Data_structure">Data Structures — Wikipedia</a></li>
<li><a title="NSSet Class Reference" href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/">NSSet Class Reference — Apple Inc.</a></li>
<li><a title="NSSet - Ry’s Objective-C Tutorial - RyPress" href="http://rypress.com/tutorials/objective-c/data-types/nsset">NSSet — RyPress</a></li>
<li><a title="Collection Data Structures In Swift - Ray Wenderlich" href="http://www.raywenderlich.com/79850/collection-data-structures-swift">Collection Data Structures In Swift — Ray Wenderlich</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-set-type/">Swift Set Type</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Multiple Optional Bindings in Swift</title>
		<link>https://www.codingexplorer.com/multiple-optional-bindings-swift-1-2/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 11 Feb 2015 17:36:52 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=962</guid>

					<description><![CDATA[<p>Shortly after my last post Segue from UITableViewCell Taps in Swift, Apple released Xcode 6.3 Beta 1, which includes Swift 1.2.  There are many updates to the language that I was quite happy about, but let&#8217;s talk about my favorite one today, improved Optional Binding. The new version allows you to bind multiple optionals, as well [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/multiple-optional-bindings-swift-1-2/">Multiple Optional Bindings in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Shortly after my last post <a title="Segue from UITableViewCell Taps in Swift" href="http://www.codingexplorer.com/segue-uitableviewcell-taps-swift/">Segue from UITableViewCell Taps in Swift</a>, Apple released Xcode 6.3 Beta 1, which includes Swift 1.2.  There are many updates to the language that I was quite happy about, but let&#8217;s talk about my favorite one today, improved Optional Binding.</p>
<p>The new version allows you to bind multiple optionals, as well as check a boolean expression related to them in a single line, avoiding the nesting we currently must do when working with multiple Optional Bindings.<br />
<span id="more-962"></span></p>
<h2>Multiple Optional Bindings — Avoid the &#8220;Pyramid of Doom&#8221;</h2>
<p>So, I apparently called what everybody else calls the &#8220;Pyramid of Doom&#8221; the &#8220;Tower of Ifs&#8221; in my previous article, despite hearing of the Pyramid from the <a title="iTunes - Podcasts - Edge Cases by Andrew Pontious and Wolf Rentzsch" href="https://itunes.apple.com/us/podcast/edge-cases/id538007855?mt=2&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-MultipleOptionalBindingsSwift12">Edge Cases</a> podcast, ah well.  They were more talking about highly nested callbacks via blocks or closures, which isn&#8217;t exactly this, but the nesting required for multiple Optional Bindings in early Swift make the term appropriate in this context as well.  Nonetheless, with this improvement, let&#8217;s look at what we wrote last time for prepareForSegue:</p>
<h3>Before Multiple Optional Bindings Version</h3>
<pre class="lang:swift decode:true">override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == blogSegueIdentifier {
                if let destination = segue.destination as? BlogViewController {
                    if let blogIndex = tableView.indexPathForSelectedRow?.row {
                        destination.blogName = swiftBlogs[blogIndex]
            }
        }
    }
}</pre>
<p>Like I said before, I&#8217;m not a fan of that Pyramid of Doom there.  Now, you can chain multiple if-let statements, which would result in the following code:</p>
<h3>After Multiple Optional Bindings Version (First Refactor)</h3>
<pre class="lang:swift decode:true">override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == blogSegueIdentifier {
        if let destination = segue.destination as? BlogViewController,
           let blogIndex = tableView.indexPathForSelectedRow?.row
        {
            destination.blogName = swiftBlogs[blogIndex]
        }
    }
}</pre>
<p>Since we only had 2 if-let statements, it doesn&#8217;t look a WHOLE lot better, but it does keep us from needlessly nest the code.  This is especially important if there was an else associated with this if statement (then there would be elses nested in there, and that would look even worse).  Thanks to <a title="Colin Eberhardt (@ColinEberhardt) | Twitter" href="https://twitter.com/ColinEberhardt">Colin Eberhardt</a> for pointing even more issues (and a little history on the term) on his post <a title="Tearing Down Swift's Optional Pyramid of Doom" href="http://www.scottlogic.com/blog/2014/12/08/swift-optional-pyramids-of-doom.html">Tearing Down Swift&#8217;s Optional Pyramid of Doom</a>.  He also goes into some ways to deal with this before this change was implemented using some functional programming.  It&#8217;s definitely an interesting read.</p>
<h2>Multiple Optional Bindings with Normal Boolean Conditional</h2>
<p>We <em>could</em> have used the <strong>where</strong> clauses discussed below to remove 1 more level of nesting in the above example, but that use is inconsistent with how <strong>where</strong> is used in other contexts, usually checking the objects it is working on, or components thereof.  The segue identifier, nor the blogSegueIdentifier are components of the destination of blogIndex, so it seemed like bad practice to me.  Now, we have a better option!</p>
<p>Now, we can start with a normal if-statement if we want, and then continue with Optional Binding when the initial if-statement evaluates to true, so, now, the above example becomes:</p>
<h3>After Multiple Optional Bindings Version (Second Refactor)</h3>
<pre class="lang:swift decode:true">override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if  segue.identifier == blogSegueIdentifier,
        let destination = segue.destination as? BlogViewController,
        let blogIndex = tableView.indexPathForSelectedRow?.row
    {
        destination.blogName = swiftBlogs[blogIndex]
    }
}</pre>
<p>There we have it.  While the conditional itself is rather long, it is in ONE level of nesting.  There isn&#8217;t much we would do if it was the correct segue, but the destination and blogIndex couldn&#8217;t be optionally bound, we don&#8217;t really need to have an else for each of those individual cases.  If any of these evaluate to false, the whole conditional fails, and we don&#8217;t have to worry about dealing with multiple else clauses for the intermediate if-statements.</p>
<p>If you need those, you can do it the old way, but especially when you have many optionals to use, getting into 5 levels or more of nesting can get a bit&#8230; interesting to work with.  Maybe somebody might want the intermediate levels when debugging, but all that really does here is let you know if the destination isn&#8217;t a BlogViewController (which really should be caught in testing, rather than with &#8220;else&#8221; clauses in production code), or if there is no selected row in the tableView (which shouldn&#8217;t happen because that is what starts this particular segue, unless it was cleared beforehand, I suppose).</p>
<p>If you had more than one segue you would probably use a switch statement instead of an if-statement.  If you only have a small amount though, this could still be of use.  You can read more about Switch statements in the earlier post <a title="Loops, Switch Statements, and Ranges in Swift" href="http://www.codingexplorer.com/loops-switch-statements-ranges-swift/">Loops, Switch Statements, and Ranges in Swift</a>.</p>
<p>Now we can have all of our Multiple Optional Bindings and conditional checking in one line.  Is it almost as verbose as the original way?  Yes, since we still have to write the code to actually do what we need (like reading the indexPath and casting the destinationviewController).  However though, we do not have to nest multiple Optional Bindings inside themselves, and that&#8217;s the important part.</p>
<h2>Conclusion</h2>
<p>I am also a fan of the delayed initialization of constants (&#8220;let&#8221; values), requiring them to by initialized before they are used, but not necessarily when they&#8217;re declared.  Type casting has seen some changes as well, and NSSet finally gets a Swift equivalent called Set.  You can read about the new Set type in the newer post <a title="Swift Set Type in Swift 1.2" href="http://www.codingexplorer.com/swift-set-type/">Swift Set Type</a>.</p>
<p>As far as non-syntax changes, I am glad they have add incremental building, so that every Swift file does not need to be recompiled each time, particularly if only one has been changed.  They have also better optimized many things under the hood, especially for Debug builds.</p>
<p>I am glad since the original writing of this post, that they changed the indexPathForSelectedRow from a method to a property, since it really was just a getter method in the first place.  It might be just a couple less parentheses, but it still makes it look just a bit cleaner.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="The Swift Programming Language: Document Revision History" href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/RevisionHistory.html#//apple_ref/doc/uid/TP40014097-CH40-ID459">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/multiple-optional-bindings-swift-1-2/">Multiple Optional Bindings in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Segue from UITableViewCell Taps in Swift</title>
		<link>https://www.codingexplorer.com/segue-uitableviewcell-taps-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 09 Feb 2015 18:20:09 +0000</pubDate>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[optionals]]></category>
		<category><![CDATA[properties]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=948</guid>

					<description><![CDATA[<p>In many apps that use a UITableView, when a UITableViewCell is tapped, the screen will segue over to another view, such as how choosing a song in the Music app goes to the Now Playing screen, and plays that song, shows the album art, and other metadata about the song.  This can be done programmatically in tableView:didSelectRowAtIndexPath:, but [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/segue-uitableviewcell-taps-swift/">Segue from UITableViewCell Taps in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="800" height="400" src="https://www.codingexplorer.com/wp-content/uploads/2015/02/UITableViewCellSegueTitle.png" class="rss-featured-image wp-post-image" alt="" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/02/UITableViewCellSegueTitle.png 800w, https://www.codingexplorer.com/wp-content/uploads/2015/02/UITableViewCellSegueTitle-300x150.png 300w" sizes="auto, (max-width: 800px) 100vw, 800px" /><p>In many apps that use a UITableView, when a UITableViewCell is tapped, the screen will segue over to another view, such as how choosing a song in the Music app goes to the Now Playing screen, and plays that song, shows the album art, and other metadata about the song.  This can be done programmatically in tableView:didSelectRowAtIndexPath:, but with Storyboards, it is even easier.  All we have to do is set up a segue, and treat it pretty much exactly like we did in <a title="Segue between Swift View Controllers" href="http://www.codingexplorer.com/segue-swift-view-controllers/">Segue between Swift View Controllers</a>.</p>
<p>To avoid an even longer setup section, and to not cover things we already covered, we&#8217;re going to start with the result of the previous post <a title="Getting Started With UITableView in Swift" href="http://www.codingexplorer.com/getting-started-uitableview-swift/">Getting Started With UITableView in Swift</a>.</p>
<p>Anyway, starting from where we left off, let&#8217;s set up the storyboard.<br />
<span id="more-948"></span></p>
<h2>Setting up the Storyboard</h2>
<p>Our last version of this tutorial had a UITableView list off a number of Swift blogs.  This tutorial is going to be a very simple extension if it, where when the user taps on a cell, it will load another view controller that will state which blog it is about in a UILabel.  It would probably be fancier to actually put a UIWebView in here and actually load the page, but we aren&#8217;t here to learn about UIWebViews today, we&#8217;re here to learn about segueing from a UITableViewCell and customizing that next view controller.</p>
<p>As such, let&#8217;s make up a simple view controller that just has 2 UILabels, one static one to say that this screen is about a blog, and the other one we&#8217;ll update to the blog we want to talk about, set it up to look like so:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/02/01-BlogVC.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-949" src="http://www.codingexplorer.com/wp-content/uploads/2015/02/01-BlogVC.png" alt="01-BlogVC" width="610" height="642" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/02/01-BlogVC.png 610w, https://www.codingexplorer.com/wp-content/uploads/2015/02/01-BlogVC-285x300.png 285w" sizes="auto, (max-width: 610px) 100vw, 610px" /></a></p>
<p>If you want to make it pretty with Auto Layout, set the top UILabel to center horizontally, with space to the top margin.  Then tell the second UILabel to align it&#8217;s center with the top one, and have some vertical space between them as well.  You can read up a bit more about using Auto Layout in the post <a title="Hello World! Your first iOS App in Swift" href="http://www.codingexplorer.com/hello-world-first-ios-app-swift/">Hello World! Your first iOS App in Swift</a>.</p>
<p>Next, we&#8217;re going to push to this view in a UINavigationController, so let&#8217;s embed our initial View Controller with the UITableView in it in a Navigation Controller.  So, select the first view controller, and then go to the top menu and click on Editor → Embed In → Navigation Controller.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/03-EmbedNavigation.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-867" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/03-EmbedNavigation.png" alt="03-EmbedNavigation" width="471" height="219" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/03-EmbedNavigation.png 471w, https://www.codingexplorer.com/wp-content/uploads/2015/01/03-EmbedNavigation-300x139.png 300w" sizes="auto, (max-width: 471px) 100vw, 471px" /></a></p>
<p>Just to note, that screenshot was taken when this post was originally written (6.1.1), so the menu above is lacking the option of &#8220;Stack View&#8221;, be we aren&#8217;t using it in this tutorial anyway.  With that done, we then make a segue from the prototype UITableViewCell (either directly in the storyboard, or through the Document Outline, both will work).  Ctrl+Drag from the UITableViewCell to our new view controller.  You will then be presented with this dialog about what segue to create:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/02/02-CellSegue.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-950" src="http://www.codingexplorer.com/wp-content/uploads/2015/02/02-CellSegue.png" alt="02-CellSegue" width="209" height="283" /></a></p>
<p>For this, we are going to select the &#8220;<strong>show</strong>&#8221; segue in the &#8220;Selection Segue&#8221; section.  This means that when you tap on the cell, it will cause this segue to happen.  If you use the &#8220;Accessory Action&#8221; one, that will be what happens if they tap on the accessory of the UITableViewCell.  For instance, in <a title="Marco.org" href="http://www.marco.org/">Marco Arment</a>&#8216;s <a title="Overcast: Podcast Player on the App Store on iTunes" href="https://itunes.apple.com/us/app/overcast-podcast-player/id888422857?mt=8&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-uitableviewsegue">Overcast App</a>, on the right side of a podcast in the podcast episode list, there is a little &#8220;i&#8221; information symbol in the accessory view area.  If you tap anywhere else in the cell, it starts playing that podcast, and goes to the &#8220;Now Playing&#8221; screen.  If you tap that little &#8220;i&#8221; symbol, it will show a popover with additional information about that podcast episode.  If I had to guess, that is done with the &#8220;popover presentation&#8221; in the &#8220;Accessory Action&#8221; section above, but I have not tested this yet.</p>
<p>Select that segue, and in the Attributes Inspector, give it an identifier with the name &#8220;ShowBlogSegue&#8221;:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/02/03-TableViewCEllSegueIdentifier.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-951" src="http://www.codingexplorer.com/wp-content/uploads/2015/02/03-TableViewCEllSegueIdentifier.png" alt="03-TableViewCEllSegueIdentifier" width="257" height="75" /></a></p>
<p>We&#8217;re going to need a custom class for our new view controller, so create one from the top menu via File → New → File&#8230;, in which we will create a &#8220;Cocoa Touch Class&#8221; in the iOS → Source section.  Make sure it is a subclass of &#8220;UIViewController&#8221;, and name it &#8220;BlogViewController&#8221;.  After that, go back to the Storyboard, select the second View Controller, and go to the &#8220;Identity Inspector&#8221; in the Utility pane.  In there, set the Class to our new class &#8220;BlogViewController&#8221;.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/02/04-BlogViewController.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-952" src="http://www.codingexplorer.com/wp-content/uploads/2015/02/04-BlogViewController.png" alt="04-BlogViewController" width="258" height="68" /></a></p>
<p>Now, select the BlogViewController on the storyboard and open the Assistant Editor, and you should see BlogViewController.swift as the correct counterpart in that text editor.  Ctrl+Drag from our &#8220;???&#8221; UILabel onto there, and create an outlet named &#8220;blogNameLabel&#8221;.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/02/05-blogNameLabelOutlet.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-953" src="http://www.codingexplorer.com/wp-content/uploads/2015/02/05-blogNameLabelOutlet.png" alt="05-blogNameLabelOutlet" width="308" height="165" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/02/05-blogNameLabelOutlet.png 308w, https://www.codingexplorer.com/wp-content/uploads/2015/02/05-blogNameLabelOutlet-300x161.png 300w" sizes="auto, (max-width: 308px) 100vw, 308px" /></a></p>
<p>We&#8217;re almost done.  This last thing is just cosmetic, but if a UITableViewCell pushes a new view over the UITableView&#8217;s view controller, it is customary for it to have a &#8220;&gt;&#8221; accessory, called a &#8220;Disclosure Indicator&#8221;.  Tapping this accessory won&#8217;t do anything different for this app, but it&#8217;s best to follow convention in how it should look.  So, select the UITableViewCell prototype, and change it&#8217;s &#8220;Accessory&#8221; to &#8220;Disclosure Indicator&#8221; in the Attributes Inspector.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/02/06-BlogDisclosureIndicator.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-954" src="http://www.codingexplorer.com/wp-content/uploads/2015/02/06-BlogDisclosureIndicator.png" alt="06-BlogDisclosureIndicator" width="236" height="68" /></a></p>
<p>With that, now let&#8217;s get to the code.</p>
<h2>Set up Destination View Controller</h2>
<p>Now, click on &#8220;BlogViewController.swift&#8221; and let&#8217;s get this one set up.  We&#8217;ll need a variable to place the Swift String of the blog name.  We will use that in viewWillAppear to set the text of the blogNameLabel outlet we made earlier:</p>
<pre class="lang:swift decode:true">var blogName = String()

override func viewWillAppear(_ animated: Bool) {
    blogNameLabel.text = blogName
}</pre>
<p>That&#8217;s it for BlogViewController.swift</p>
<h2>PrepareForSegue in Main View Controller</h2>
<p>This will look pretty familiar to those that read <a title="Segue between Swift View Controllers" href="http://www.codingexplorer.com/segue-swift-view-controllers/">Segue between Swift View Controllers</a>, but there is one new thing.  We need to get the index for the cell that was tapped, so we can get the Swift String associated with it from the swiftBlogs array.  We&#8217;ll do that with the tableView method &#8220;indexPathForSelectedRow()&#8221;.  This results in the code below:</p>
<pre class="lang:swift decode:true">let blogSegueIdentifier = "ShowBlogSegue"

// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if  segue.identifier == blogSegueIdentifier,
        let destination = segue.destination as? BlogViewController,
        let blogIndex = tableView.indexPathForSelectedRow?.row
    {
        destination.blogName = swiftBlogs[blogIndex]
    }
}</pre>
<p>So first, we set a constant for the &#8220;ShowBlogSegue&#8221; identifier.  Inside of prepareForSegue, we check if that is the identifier for the segue requested.  If it is, we type cast the destination View Controller to a BlogViewController type, if that indeed is what it should be.  Then, we&#8217;ll save the row from the NSIndexPath returned from tableView.indexPathForSelectedRow().  It returns an optional, if somehow the indexPath was invalid, so we optionally bound it to the &#8220;blogIndex&#8221; constant.</p>
<p>Finally, when all of that is done, we set the &#8220;blogName&#8221; property of the destination View Controller to the Swift String stored in the swiftBlogs array, at the blogIndex we just got.</p>
<p>With that done, run your program, and you should be able to tap on the different blogs in the UITableView and segue over to the BlogViewController to see which one was tapped on.</p>
<h2>Note about AutoLayout and Size Classes</h2>
<p>When I was testing this, at this point, everything <em>worked</em> fine at this point, but I noticed that I couldn&#8217;t see the disclosure indicators.  Turns out it was an issue with Auto Layout and Size classes that I just forgot to deal with earlier.  You can see the disclosure indicator just fine in the editor, but notice that the box is much wider than a normal iPhone interface?  So if you aren&#8217;t seeing the disclosure indicators, they probably are THERE, but they&#8217;re farther to the right than your screen is showing.  I just simply selected the UITableView from the Document Outline, and Pinned all of its sides (top, bottom, left and right) to 0 with &#8220;Constrain to margins&#8221; off.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/02/07-BlogTableViewPin.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-955" src="http://www.codingexplorer.com/wp-content/uploads/2015/02/07-BlogTableViewPin.png" alt="07-BlogTableViewPin" width="233" height="164" /></a></p>
<p>Then just run again, and your disclosure indicators should be visible.</p>
<h2>Code for UITableViewCell Segue Tutorial View Controllers</h2>
<p>For the sake of completion, here is the code for both view controllers:</p>
<h3>ViewController.swift</h3>
<pre class="lang:swift decode:true">import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var tableView: UITableView!
    
    let textCellIdentifier = "TextCell"
    
    let blogSegueIdentifier = "ShowBlogSegue"   //New
    
    let swiftBlogs = ["Ray Wenderlich", "NSHipster", "iOS Developer Tips", "Jameson Quave", "Natasha The Robot", "Coding Explorer", "That Thing In Swift", "Andrew Bancroft", "iAchieved.it", "Airspeed Velocity"]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }
    
    //New
    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if  segue.identifier == blogSegueIdentifier,
            let destination = segue.destination as? BlogViewController,
            let blogIndex = tableView.indexPathForSelectedRow?.row
        {
            destination.blogName = swiftBlogs[blogIndex]
        }
    }
    
    // MARK: - UITextFieldDelegate Methods
    func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
        return swiftBlogs.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)
        
        let row = indexPath.row
        cell.textLabel?.text = swiftBlogs[row]
        
        return cell
    }
    
    // MARK: - UITableViewDelegate Methods
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let row = indexPath.row
        print(swiftBlogs[row])
    }
}</pre>
<h3>BlogViewController.swift</h3>
<pre class="lang:swift decode:true ">import UIKit

class BlogViewController: UIViewController {
    
    @IBOutlet var blogNameLabel: UILabel!
    
    var blogName = String()

    override func viewWillAppear(_ animated: Bool) {
        blogNameLabel.text = blogName
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}</pre>
<h2>Conclusion</h2>
<p><strong>Screenshots taken from Xcode 6.1.1, code checked against version listed at top of the post.</strong></p>
<p>In the previous post, I had mentioned about using tableView:didSelectRowAtIndexPath:.  You can use that if you are doing this programmatically, but since we have Storyboards at our disposal, I realized that would be a much better way to handle this.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/segue-uitableviewcell-taps-swift/">Segue from UITableViewCell Taps in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Dismiss UITextField&#8217;s Keyboard in your Swift App</title>
		<link>https://www.codingexplorer.com/how-to-dismiss-uitextfields-keyboard-in-your-swift-app/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 28 Jan 2015 17:01:27 +0000</pubDate>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=927</guid>

					<description><![CDATA[<p>If you need to take text input in your Swift app, you will probably need a UITextField.  It is exactly what it sounds like, just a field on the screen where the user types something in.  When the user taps on it, the keyboard comes up from the bottom of the screen, and allows the [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/how-to-dismiss-uitextfields-keyboard-in-your-swift-app/">How to Dismiss UITextField&#8217;s Keyboard in your Swift App</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="600" height="300" src="https://www.codingexplorer.com/wp-content/uploads/2015/01/UITextFieldKeyboardTitle.png" class="rss-featured-image wp-post-image" alt="" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/UITextFieldKeyboardTitle.png 600w, https://www.codingexplorer.com/wp-content/uploads/2015/01/UITextFieldKeyboardTitle-300x150.png 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /><p>If you need to take text input in your Swift app, you will probably need a UITextField.  It is exactly what it sounds like, just a field on the screen where the user types something in.  When the user taps on it, the keyboard comes up from the bottom of the screen, and allows the user to start typing.  Then, usually, when the user clicks outside of the UITextField, the keyboard is dismissed, and the cursor is no longer in that UITextField.</p>
<p>However, a common issue for many iOS programming beginners is that the last part of that story isn&#8217;t built in.  If you just plop on a UITextField, and try tapping somewhere else&#8230;. nothing happens.  That&#8217;s what we&#8217;re here to fix today.<br />
<span id="more-927"></span></p>
<h2>Setting up the Storyboard</h2>
<p>Okay, THIS post should probably have the shortest storyboard setup section so far.  Start a new project, and name it &#8220;TextFieldTutorial&#8221;.  Once complete, drag on a UITextField somewhere.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/01-TextFieldObject.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-928" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/01-TextFieldObject.png" alt="01-TextFieldObject" width="252" height="243" /></a></p>
<p>If you don&#8217;t want to mess with Auto Layout today, just put it in the top left.  Otherwise, place it somewhere in the top area of the screen, and set up Auto Layout as appropriate.  You can read the earlier post <a title="Hello World! Your first iOS App in Swift" href="http://www.codingexplorer.com/hello-world-first-ios-app-swift/">Hello World! Your first iOS App in Swift</a> for some help on project setup and Auto Layout if you want a bit more information.</p>
<p>The Attributes Inspector has a lot of options that you can change for your UITextField if you wish.  We aren&#8217;t going to change any of them today, but if you are curious, you can change the type of keyboard that shows up for you with the &#8220;Keyboard Type&#8221; combo-box.  I&#8217;m not sure how these interact with 3rd party keyboards though.  It might ask them for a version that best approximates these selections, or it might ignore them.  I&#8217;ve not worked with writing any custom keyboards yet, so I have only conjecture to guide me in how this selection works with them.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/02-Keyboards.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-929" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/02-Keyboards.png" alt="02-Keyboards" width="237" height="267" /></a></p>
<p>&nbsp;</p>
<p>That&#8217;s all.  See, I told you this would be a short one.  We don&#8217;t even need an outlet in your Swift file for this tutorial!  If you want to actually read something from the UITextField, you&#8217;ll need one, but we&#8217;re here just to learn how to dismiss the keyboard.</p>
<h2>Dismissing the UITextField&#8217;s Keyboard</h2>
<p>Now, go to your ViewController&#8217;s Swift file.  There are a few ways to do this, but this is the way I usually do it.</p>
<p>We are going to override the method touchesBegan:withEvent: for the ViewController itself.  This is called when the view sees a touch event (as it begins, appropriately).  In it, we are simply going to tell our main view to end editing, like so:</p>
<pre class="lang:swift decode:true">override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
    view.endEditing(true)
    super.touchesBegan(touches, with: event)
}</pre>
<p>That&#8217;s all there is to it.  Once you tap outside of the UITextField, the keyboard will be dismissed.  How does this work?  I&#8217;ll let the <a title="UIView Class Reference" href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/endEditing:">Apple Documentation</a> for the <strong>endEditing</strong> method speak for itself:</p>
<blockquote>
<p class="p1"><span class="s1">This method looks at the current view and its subview hierarchy for the text field that is currently the first responder. If it finds one, it asks that text field to resign as first responder. If the </span><span class="s2"><i>force</i></span><span class="s1"> parameter is set to </span><span class="s3">YES</span><span class="s1">, the text field is never even asked; it is forced to resign.</span></p>
</blockquote>
<p>This is why we didn&#8217;t need an outlet in our Swift file to the UITextField to dismiss it.  This basically just asks any UITextField if it is the first responder, and if it is, tells it to resign being so.</p>
<p>The first responder concept is pretty much what it sounds like, though that doesn&#8217;t help much in explaining it without a bit of context.  For programs using both AppKit and UIKit, there is something called the &#8220;Responder Chain&#8221;.  The &#8220;first&#8221; responder is the part in that chain that responds to events first.  In this case, we have a UITextField that will intercept the keyboard events when typing first.  Since you clicked on the UITextField, it really should be the one handling the keyboard events, as opposed to the View that it is in, or the UIApplication itself at the top.  I&#8217;m still pretty new to the concept in general, so to learn more, you can read <a title="Responder object" href="https://developer.apple.com/library/ios/documentation/General/Conceptual/Devpedia-CocoaApp/Responder.html">Apple&#8217;s Responder object page</a>.</p>
<p>Suffice it to say, the keyboard shows up when the UITextField is first responder, and when you ask it to resign that status, the keyboard is dismissed.</p>
<p>The final line call&#8217;s UITextField&#8217;s superclass to run the same method as well, which allows it to go further up the responder chain.  This allows the system to handle this, and other related touch events, appropriately.  If you don&#8217;t call it, then the <a title="UIResponder Class Reference" href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/index.html#//apple_ref/occ/instm/UIResponder/touchesBegan:withEvent:">UIResponder Class Reference</a> suggests overriding the other touch event handling methods, at least as stub implementations.  It&#8217;s probably easier to just pass it up the chain, unless you really need special handling for the Moved, Ended, and Cancelled touch event methods.</p>
<p>On that note, if you DID make an outlet in your Swift file, another way is to simply ask that object to resign its first responder status, if it has one:</p>
<pre class="lang:swift decode:true">textField.resignFirstResponder()</pre>
<p>However, if you have more than one, and you do this in the touchesBegan method, you&#8217;ll have to ask all of them.  I see both ways suggested online, and have yet to learn a good reason to use one over the other.  I&#8217;m not sure if forcing it to relinquish its first responder status is necessary always either.  In my tests, they both dismissed the keyboard just fine, but I&#8217;m not sure how to make UITextField say no when it is asked to resign as first responder (other than to override the method that actually provides the answer directly).  You can try it out in your Swift apps with a false value if you wish, it is probably nicer to ask than to demand it resign being First Responder.</p>
<p>Nonetheless, it is your choice which one to use.  When I learn more, I&#8217;ll update here to pass on the information if I have done this in a way that is not best practice.</p>
<p>This method does have some issues in other contexts, like scroll views.  In those cases, you would have to add a gesture recognizer to that view, and in that gesture recognizer&#8217;s action method, you would have to call one of the above methods to dismiss the keyboard.</p>
<h2>Conclusion</h2>
<p><strong>Screenshots taken from Xcode 6.1.1, code checked against version listed at top of the post.</strong></p>
<p>We can talk more about using UITextField in Swift another time, as well as its delegate UITextFieldDelegate, which allows more control over what happens (most notably when editing is finished).</p>
<p>If you want me to cover the other ways, like the gesture recognizer style, please let me know.  Also, if you feel this really shouldn&#8217;t be done with a force endEditing call, I would love to hear why, and maybe pass it on to the rest of you.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="UIView Class Reference" href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/endEditing:">UIView Class Reference — Apple Inc.</a></li>
<li><a title="Responder object" href="https://developer.apple.com/library/ios/documentation/General/Conceptual/Devpedia-CocoaApp/Responder.html">Responder object — Apple Inc</a>.</li>
<li><a title="UIResponder Class Reference" href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/index.html#//apple_ref/occ/instm/UIResponder/touchesBegan:withEvent:">UIResponder Class Reference — Apple Inc.</a></li>
<li><a title="Dismiss keyboard when tap outside a UITextField/UITextView — Junda Ong" href="http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/">Dismiss keyboard when tap outside a UITextField/UITextView — Junda Ong</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/how-to-dismiss-uitextfields-keyboard-in-your-swift-app/">How to Dismiss UITextField&#8217;s Keyboard in your Swift App</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Getting Started With UITableView in Swift</title>
		<link>https://www.codingexplorer.com/getting-started-uitableview-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 26 Jan 2015 18:33:58 +0000</pubDate>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[optionals]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=904</guid>

					<description><![CDATA[<p>One of the most common Views used in iOS apps is the UITableView.  In the default iPhone apps alone, the only ones that I didn&#8217;t easily find what is PROBABLY a UITableView was in Newsstand, Videos, Camera, and the Calculator.  Even then, the first two of those appear to use UITableView&#8217;s close cousin UICollectionView.  With [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/getting-started-uitableview-swift/">Getting Started With UITableView in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="800" height="400" src="https://www.codingexplorer.com/wp-content/uploads/2015/01/UITableViewTitle.png" class="rss-featured-image wp-post-image" alt="" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/UITableViewTitle.png 800w, https://www.codingexplorer.com/wp-content/uploads/2015/01/UITableViewTitle-300x150.png 300w" sizes="auto, (max-width: 800px) 100vw, 800px" /><p>One of the most common Views used in iOS apps is the UITableView.  In the default iPhone apps alone, the only ones that I didn&#8217;t easily find what is PROBABLY a UITableView was in Newsstand, Videos, Camera, and the Calculator.  Even then, the first two of those appear to use UITableView&#8217;s close cousin UICollectionView.  With the exception of the Settings app itself, I wasn&#8217;t even counting their settings pages (which probably all of them have, and show up as a UITableView either in their own app or via the Settings app).</p>
<p>You probably want to know how to use such an important view?  There is too much to go into all of it today, but let&#8217;s start out with how to get one working and fill it with data.<br />
<span id="more-904"></span><br />
So first, start a new Single View Application.  Let&#8217;s call it the imaginative name &#8220;TableViewTutorial&#8221; (I know, creative genius, right?).  Fill in the organization name and identifier as you normally would.  You can set devices to whatever you want, but I left mine as &#8220;Universal&#8221;, and of course the language should be &#8220;Swift&#8221;!  If you need help with this part of the tutorial, please see the post <a title="Hello World! Your first iOS App in Swift" href="http://www.codingexplorer.com/hello-world-first-ios-app-swift/">Hello World! Your first iOS App in Swift</a>, which covers this section in much greater detail.</p>
<h2>Set up the Storyboard</h2>
<p>This is probably going to be the shortest storyboard setup that I&#8217;ve done on these tutorials.  There are basically two ways to do this step.  I am going to go for putting a UITableView into a normal ViewController.  There is another object called the UITableViewController as well.  If you want ONLY a UITableView on your screen, and that&#8217;s it (well, besides a UINavigationController or UITabBarController), then you can choose this option.  I&#8217;ve run into issues if I wanted to add something else to the screen like a toolbar, which you cannot do in a UITableViewController.  While we won&#8217;t be taking advantage of the benefits of using a UITableView in a normal UIViewController in this post, I felt it best to show the most flexible form.  If you understand how to do it with this version, than using a UITableViewController will be a piece of cake.</p>
<p>So, as the above paragraph is talking about, drag a UITableView from the Object Library and put it onto your ViewController in the Main.storyboard file.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/01-TableViewObject.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-907" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/01-TableViewObject.png" alt="01-TableViewObject" width="266" height="253" /></a></p>
<p>Remember it is the &#8220;Table View&#8221; object, shown in blue in the picture above.  It is NOT the &#8220;Table View Controller&#8221; with the yellow circle on the left side.</p>
<p>When you drag it onto your ViewController, the Table View will expand to fill it.  Align it to have it centered in your ViewController.  Now you will have a beautiful gray screen that says &#8220;Table View Prototype Content&#8221;.</p>
<p>With the Table View itself selected, go to the Attributes Inspector, and change the number of Prototype Cells to &#8220;1&#8221;.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/02-PrototypeCells1.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-909" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/02-PrototypeCells1.png" alt="02-PrototypeCells1" width="243" height="68" /></a></p>
<p>Now it&#8217;s looking a little more like a UITableView.  Select the new UITableViewCell (shows up as &#8220;Table View Cell&#8221; in the Document Outline).  In the Attributes Inspector, change it&#8217;s Style to &#8220;Basic&#8221;, and give it the Identifier &#8220;TextCell&#8221;.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/03-CellStyleIdentifier.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-910" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/03-CellStyleIdentifier.png" alt="03-CellStyleIdentifier" width="255" height="92" /></a></p>
<p>Open the Assistant Editor, and Ctrl+Drag from your UITableView to somewhere in your code.  We are making an outlet for the UITableView in our ViewController code, so that we can access it to modify things.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/04-tableViewOutlet.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-911" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/04-tableViewOutlet.png" alt="04-tableViewOutlet" width="322" height="160" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/04-tableViewOutlet.png 322w, https://www.codingexplorer.com/wp-content/uploads/2015/01/04-tableViewOutlet-300x149.png 300w" sizes="auto, (max-width: 322px) 100vw, 322px" /></a></p>
<p>With that, we should be done in the Storyboard.  Now, TO THE CODE!</p>
<h2>Filling the UITableViewController</h2>
<p>Now here, there are a few ways to do this one.  We&#8217;ll go over the EASIEST way today, but it may not be the best.  To use a UITableView, you have to create objects that will serve as the DataSource and Delegate to it.  The DataSource does what it says, it is what the UITableView will talk to in order to know what data to show in the UITableView.  The Delegate is primarily to control HOW this data is displayed.  There is a bit of overlap, and the Delegate often needs to talk to the DataSource as well, but this is what I have seen thus far as the difference between the two.</p>
<p>In this tutorial, we are going to make this ViewController be the DataSource and the Delegate.  Is this really the job of the ViewController?  I&#8217;m still trying to figure that out myself.  In one app I&#8217;ve been working on, I&#8217;ve split up the DataSource and the Delegate to two separate files outside of the main ViewController file.  Since the delegate has to request information from the DataSource though, I have the Delegate taking in the DataSource as an injected dependency.  I&#8217;ve heard that since they talk so much, it might be best to have the Delegate and the DataSource be in the same class, but have that class file separate from your ViewController itself.  In short, today we will have 1 class to rule them all.  It can be split to 3 (separate ViewController, DataSource, and Delegate), but due to dependency between the DataSource and Delegate, it might be best to use 2 (ViewController and combined DataSource and Delegate).</p>
<p>For a class to be able to be used as a UITableView&#8217;s DataSource or Delegate, they must adopt the UITableViewDataSource and UITableViewDelegate protocols, respectively.  Since this tutorial will just have our ViewController do so, we add those to the class&#8217;s definition after the class&#8217;s type:</p>
<pre class="lang:swift decode:true ">class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate</pre>
<p>Now you should probably see an error show up in your sidebar, and it says:</p>
<blockquote><p>Type &#8216;ViewController&#8217; does not conform to protocol &#8216;UITableViewDataSource&#8217;</p></blockquote>
<p>Which is absolutely right. We said that it adopts the protocol, but we have not put in the required methods to actually conform to it yet.</p>
<p>We&#8217;ll cover that soon enough, but let&#8217;s finish a little setup first, since we&#8217;ll need some of it in our implementation of the appropriate methods.</p>
<p>First, we actually need a data source for this UITableViewDataSource.  Let&#8217;s just create an array, hard-coded with a few Swift Strings, which for illustrative purposes, let&#8217;s fill in with names of Swift Programming websites.  Outside of any method, create the array like so:</p>
<pre class="lang:swift decode:true">let swiftBlogs = ["Ray Wenderlich", "NSHipster", "iOS Developer Tips", "Jameson Quave", "Natasha The Robot", "Coding Explorer", "That Thing In Swift", "Andrew Bancroft", "iAchieved.it", "Airspeed Velocity"]</pre>
<p>Also, remember setting that identifier for our prototype cell?  We need to use that in the code in a little bit, and it is a whole lot easier to create a constant for this identifier and use it everywhere else.  That way, if you ever decide to change the identifier, you only have to change it in interface builder and this constant&#8217;s declaration.  If you used the straight string everywhere, you would have to change it everywhere you rewrote that string.  Here, the name of the constant will be the same, and so even if the Swift String inside it is different, the code referring to the constant itself does not need to change.  So while we&#8217;re here, let&#8217;s add that outside of any method as well:</p>
<pre class="lang:swift decode:true">let textCellIdentifier = "TextCell"</pre>
<p>Then, in the viewDidLoad method, let&#8217;s set our tableView&#8217;s DataSource and Delegate to be this class itself:</p>
<pre class="lang:swift decode:true ">override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}</pre>
<h3>Conforming to UITableViewDataSource</h3>
<p>Now, to conform to UITableViewDataSource, you must implement 3 methods:</p>
<ul>
<li>numberOfSectionsInTableView:</li>
<li>tableView:numberOfRowsInSection:</li>
<li>tableView:cellForRowAtIndexPath:</li>
</ul>
<p>Andrew Bancroft made a great resource for these on his post <a title="Swift UITableViewDataSource Cheat Sheet - Andrew Bancroft" href="http://www.andrewcbancroft.com/2014/11/24/swift-uitableviewdatasource-cheat-sheet/">Swift UITableViewDataSource Cheat Sheet</a>, with their full function prototypes and some default implementations to get you started.  We&#8217;ll cover implementations a little more specific to our example in this post, but I&#8217;m glad he made a cheat sheet for them.</p>
<p>UITableView&#8217;s can be broken up into different sections.  You can see a great example of how that&#8217;s done in the iOS Settings app.  Our app currently does not have a need for multiple sections, so for now, let&#8217;s just hard code that to 1:</p>
<pre class="lang:swift decode:true">func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
    return 1
}</pre>
<p>Next, we need to let the UITableView know how many rows are going to be in each section.  Since there is only 1 section in our UITableView, we&#8217;ll ignore that part.  However, inside that section, we have as many rows as we have elements in the array, so we&#8217;ll return the count of the elements in our array here:</p>
<pre class="lang:swift decode:true">func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
    return swiftBlogs.count
}</pre>
<p>Finally, we come to the most important method, tableView:cellForRowAtIndexPath:.  Learn to love this one, because you will be here a lot in apps that use UITableViews in them.   Here you will get a reference to the tableView requesting this information, and the indexPath it is looking for it on.  It then needs a fully setup UITableViewCell returned.</p>
<p>What we have to do is generate a UITableViewCell based off of our prototype we made in the storyboard, set its text, and return it.  We do that like so:</p>
<pre class="lang:swift decode:true">func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)

    let row = indexPath.row
    cell.textLabel?.text = swiftBlogs[row]

    return cell
}</pre>
<p>That first line is a bit of a doozy, but we&#8217;ll go through it.  To help make things more efficient, instead of creating a new cell every time, you dequeue a reusable one.  If none exist, like when the program first runs, this will actually create the new UITableViewCells.  After that though, if the user scrolls the tableview down, some UITableViewCells go offscreen on top, and new ones come below.</p>
<p>At that point, which is more important, leaving that cell in memory, ready in case the user scrolls back suddenly to see what they just passed by, or the cells that are being shown as the user continues to scroll down?  Probably the ones the user is about to see.</p>
<p>So, to save having to waste processor cycles creating a new UITableViewCell object, and RAM to hold offscreen ones in case the user scrolls back, the system will decide to return one of those already created, but offscreen UITableViewCells when dequeueReusableCellWithIdentifier is called.</p>
<p>Using that identifier constant we created earlier, we request a cell based off of our prototype.</p>
<p>Since the original writing of this post, UITableView&#8217;s API has been updated.  The method dequeueReusableCellWithIdentifier:forIndexPath used to return an object of the type AnyObject, which we had to typecast back into a UITableViewCell.  Now, it just returns a a UITableViewCell object itself, so no type casting is required in this tutorial.  If you had a custom UITableViewCell, that has more than just what the basic one offers, you would have to type cast there to set the properties associated with that custom cell, but in this app, we just use the basic style.  You can read more about type casting in the previous post <a title="Type Casting in Swift" href="http://www.codingexplorer.com/type-casting-swift/">Type Casting in Swift</a>.</p>
<p>There are actually two versions of this method, the other one does not have indexPath as a component.  I am still new to it, but according to this <a title="ios - When to use dequeueReusableCellWithIdentifier vs dequeueReusableCellWithIdentifier : forIndexPath - Stack Overflow" href="http://stackoverflow.com/questions/25826383/when-to-use-dequeuereusablecellwithidentifier-vs-dequeuereusablecellwithidentifi">Stack Overflow thread</a>, the major difference is how the reusable cells are registered (which the Storyboard handles for us in our tutorial&#8217;s case), and how it reacts.</p>
<p>Apparently if we create our cell prototype in code, and did not register it as a reusable cell, the older (non-indexPath) method return nil.  This one asserts to crash the program (on purpose to make this error VERY obvious).  I think the indexPath inside helps with sizing and preparing the cell in some other ways, but I&#8217;m really not sure entirely what the indexPath is used for in this form (so far).</p>
<p>As far as UITableView is concerned, an NSIndexPath is a way for the system to refer to a specific row in a specific section.  In the more general case (according to <a title="NSIndexPath Class Reference" href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/index.html">NSIndexPath Class Reference</a>) &#8220;The NSIndexPath class represents the path to a specific node in a tree of nested collections.&#8221;  So in our next line, we save the &#8220;row&#8221; property of this indexPath to a local Swift Int constant also named &#8220;row&#8221; (mostly for readability).</p>
<p>Then, we set the text of the cell&#8217;s textLabel to a value from our swiftBlogs array, using the indexPath&#8217;s &#8220;row&#8221; as the index in our swiftBlogs array lookup.</p>
<p>Finally, we return this cell.</p>
<h3>Conforming to UITableViewDelegate</h3>
<p>You may notice that now that we have implemented those 3 methods for the UITableViewDataSource protocol, we have no errors relating to not conforming to the UITableViewDelegate protocol.  That is because all of the methods in the UITableViewDelegate protocol are optional, you don&#8217;t have to implement any of them.  However, there are some you probably will in most UITableViews.  The most prominent of them is tableView:didSelectRowAtIndexPath:.  As its name suggests, this is called when a user selects a row at a specific indexPath (by tapping on it).  Here, we&#8217;ll simply print out what the user tapped on to the console:</p>
<pre class="lang:swift decode:true">func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let row = indexPath.row
    print(swiftBlogs[row])
}</pre>
<p>The first line deselects the row that was just selected.  If we don&#8217;t do this, the row will stay selected until another one is, leaving it highlighted.  It looks better having it highlighted temporarily, and then putting the text to the console.</p>
<p>The next lines should look familiar from tableView:cellForRowAtIndexPath:, getting the row out of the indexPath.  We then use that row in the swiftBlogs array again, but this time send that Swift String to the println function.</p>
<p>The app is finally done, run it, and you should have a UITableView filled with the names of Swift websites that will print out the selected one to the console when tapped.</p>
<p>For completeness sake, here is the full code for ViewController.swift:</p>
<pre class="lang:swift decode:true">import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var tableView: UITableView!
    
    let textCellIdentifier = "TextCell"
    
    let swiftBlogs = ["Ray Wenderlich", "NSHipster", "iOS Developer Tips", "Jameson Quave", "Natasha The Robot", "Coding Explorer", "That Thing In Swift", "Andrew Bancroft", "iAchieved.it", "Airspeed Velocity"]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }
    
    // MARK:  UITextFieldDelegate Methods
    func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
        return swiftBlogs.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)
        
        let row = indexPath.row
        cell.textLabel?.text = swiftBlogs[row]
        
        return cell
    }
    
    // MARK:  UITableViewDelegate Methods
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let row = indexPath.row
        print(swiftBlogs[row])
    }
}</pre>
<p>As a note, the &#8220;// MARK: &#8221; comment is there to make using the jump bar easier.  The jump bar is the bar above the main editor window that shows the Project, Group (Folder), File, and then method that the cursor is currently in.  You can change any of them by clicking on the section you want to change, to go to that part.  In the method part, you will see what was written in the &#8220;// MARK&#8221; comment shows up as a kind of separator in the list, making it really easy to find what you grouped together, like the methods for UITableViewDataSource, for example.</p>
<h2>Conclusion</h2>
<p><strong>Screenshots taken from Xcode 6.1.1, code checked against version listed at top of the post.</strong></p>
<p>UITableViews are an integral part of many apps.  In many of them, when you select a row, it will go to another screen to do something with it (like clicking on a song row in the Music app, goes to the &#8220;Now Playing&#8221; screen and starts playing that song).</p>
<p>Stay tuned for another tutorial soon about that, but those that want to try it for themselves, just think of what would happen if you put a certain UITableViewDelegate method together with what we learned in the earlier post <a title="Segue between Swift View Controllers" href="http://www.codingexplorer.com/segue-swift-view-controllers/">Segue between Swift View Controllers</a>.</p>
<p>That post has been written now, so check it out here — <a href="http://www.codingexplorer.com/segue-uitableviewcell-taps-swift/">Segue from UITableViewCell Taps in Swift</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="UITableView Class Reference" href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/index.html">UITableView Class Reference — Apple Inc.</a></li>
<li><a title="UITableViewDataSource Protocol Reference" href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/index.html">UITableViewDataSource Protocol Reference — Apple Inc</a>.</li>
<li><a title="UITableViewDelegate Protocol Reference" href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/index.html">UITableViewDelegate Protocol Reference — Apple Inc.</a></li>
<li><a title="ios - When to use dequeueReusableCellWithIdentifier vs dequeueReusableCellWithIdentifier : forIndexPath - Stack Overflow" href="http://stackoverflow.com/questions/25826383/when-to-use-dequeuereusablecellwithidentifier-vs-dequeuereusablecellwithidentifi">When to use dequeueReusableCellWithIdentifier vs dequeueReusableCellWithIdentifier : forIndexPath — Stack Overflow</a></li>
<li><a title="NSIndexPath Class Reference" href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/index.html">NSIndexPath Class Reference — Apple Inc</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/getting-started-uitableview-swift/">Getting Started With UITableView in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Create a UIColor in Swift</title>
		<link>https://www.codingexplorer.com/create-uicolor-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 15 Jan 2015 18:13:36 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=885</guid>

					<description><![CDATA[<p>There comes a time in many iOS developers&#8217;s careers that they will need to save a reference to a color itself.  Maybe it is just to change the background color of a view, maybe it is for custom drawing, or any number of other reasons. This is where UIColor comes in.  UIColor is particularly optimized to [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/create-uicolor-swift/">How to Create a UIColor in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="600" height="300" src="https://www.codingexplorer.com/wp-content/uploads/2015/01/UIColorTitle.png" class="rss-featured-image wp-post-image" alt="" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/UIColorTitle.png 600w, https://www.codingexplorer.com/wp-content/uploads/2015/01/UIColorTitle-300x150.png 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /><p>There comes a time in many iOS developers&#8217;s careers that they will need to save a reference to a color itself.  Maybe it is just to change the background color of a view, maybe it is for custom drawing, or any number of other reasons.</p>
<p>This is where UIColor comes in.  UIColor is particularly optimized to work on iOS devices, so while there are older similar classes like CGColor or CIColor, you should probably use UIColor, unless you are working on some app that needs to translate between different colorspaces.<br />
<span id="more-885"></span></p>
<h2>Built-In UIColor Presets</h2>
<p>There are a few built in colors, which are accessed with class variables.  These are the available preset colors:</p>
<table border="1">
<tbody>
<tr>
<td>Method</td>
<td>Sample</td>
</tr>
<tr>
<td>black</td>
<td bgcolor="#000000"></td>
</tr>
<tr>
<td>darkGray</td>
<td bgcolor="#555555"></td>
</tr>
<tr>
<td>lightGray</td>
<td bgcolor="#AAAAAA"></td>
</tr>
<tr>
<td>white</td>
<td bgcolor="#FFFFFF"></td>
</tr>
<tr>
<td>gray</td>
<td bgcolor="#808080"></td>
</tr>
<tr>
<td>red</td>
<td bgcolor="#FF0000"></td>
</tr>
<tr>
<td>green</td>
<td bgcolor="#00FF00"></td>
</tr>
<tr>
<td>blue</td>
<td bgcolor="#0000FF"></td>
</tr>
<tr>
<td>cyan</td>
<td bgcolor="#00FFFF"></td>
</tr>
<tr>
<td>yellow</td>
<td bgcolor="#FFFF00"></td>
</tr>
<tr>
<td>magenta</td>
<td bgcolor="#FF00FF"></td>
</tr>
<tr>
<td>orange</td>
<td bgcolor="#FF8000"></td>
</tr>
<tr>
<td>purple</td>
<td bgcolor="#800080"></td>
</tr>
<tr>
<td>brown</td>
<td bgcolor="#996633"></td>
</tr>
<tr>
<td>clear</td>
<td></td>
</tr>
</tbody>
</table>
<p>If you need to store these, like for a background color, you would use the code:</p>
<pre class="lang:swift decode:true">let backgroundColor = UIColor.blue</pre>
<p>Notice that, since this is a class variable, you call these presets directly from the UIColor class, without having to make an instance of it.</p>
<h2>Creating a custom UIColor Object</h2>
<p>Now, the presets above are useful, but you probably will want to make your own color that is somewhere between those available colors.  In Swift, you instantiate a custom UIColor object with an initializer.</p>
<p>There are several available to us, some more useful than others:</p>
<ul>
<li style="list-style-type: none;">
<ul>
<li><span style="color: #bb2ca2;">init</span>(white: <span style="color: #703daa;">CGFloat</span>, alpha: <span style="color: #703daa;">CGFloat</span>)</li>
<li><span style="color: #bb2ca2;">init</span>(hue: <span style="color: #703daa;">CGFloat</span>, saturation: <span style="color: #703daa;">CGFloat</span>, brightness: <span style="color: #703daa;">CGFloat</span>, alpha: <span style="color: #703daa;">CGFloat</span>)</li>
<li><span style="color: #bb2ca2;">init</span>(red: <span style="color: #703daa;">CGFloat</span>, green: <span style="color: #703daa;">CGFloat</span>, blue: <span style="color: #703daa;">CGFloat</span>, alpha: <span style="color: #703daa;">CGFloat</span>)</li>
<li><span style="color: #bb2ca2;">init</span>(displayP3Red: <span style="color: #703daa;">CGFloat</span>, green: <span style="color: #703daa;">CGFloat</span>, blue: <span style="color: #703daa;">CGFloat</span>, alpha: <span style="color: #703daa;">CGFloat</span>)</li>
<li><span style="color: #bb2ca2;">init</span>(cgColor: <span style="color: #703daa;">CGColor</span>)</li>
<li><span style="color: #bb2ca2;">init</span>(patternImage image: <span style="color: #703daa;">UIImage</span>)</li>
<li><span style="color: #bb2ca2;">init</span>(ciColor: <span style="color: #703daa;">CIColor</span>)</li>
<li><span style="color: #bb2ca2;">init</span>(dynamicProvider: <span style="color: #bb2ca2;">@escaping</span> (<span style="color: #703daa;">UITraitCollection</span>) -&gt; <span style="color: #703daa;">UIColor</span>)</li>
</ul>
</li>
</ul>
<p>Each of the ones that take a CGFloat take a value between 0.0 and 1.0, referring to either the complete absence of, or the maximum amount of that color component respectively.  So, this means that even if you have pure RGB values in decimal or hexadecimal format, you will have to divide them by decimal 255 to get the amount to input here.</p>
<p>We will primarily be talking about the third one on this post.  But, for the sake of knowledge, I&#8217;ll quickly touch on the others here.</p>
<p>The first one with the &#8220;white&#8221; parameter is used to easily create grayscale values.  With 0% whiteness (0.0), you get black, with 100% whiteness (1.0) you get pure white.  Between those values you get progressively lighter grays as you go from 0 to 1.</p>
<p>The Hue-Saturation-Brightness one is still RGB based, but is another way of representing it, aiming to make it more intuitive.  I personally don&#8217;t know much about it, so I&#8217;ll point you to the <a title="HSL and HSV - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/HSL_and_HSV">HSL and HSV</a> Wikipedia page (HSV (Hue-Saturation-Value) is another name for HSB).</p>
<p>The CGColor object is a Core Graphics based color (which is lower level, and more general than UIColor).  The CIColor is a Core Image color, apparently used in Core Image based filters.</p>
<p>Finally there is the patternImage, which apparently tiles an image in to fill the area that is needing this &#8220;color&#8221;.  You can read more about it at Keith Harrison&#8217;s blog article <a title="&lt;title&gt;Using Pattern Images to Set Background Views - Use Your Loaf&lt;/title&gt;" href="http://useyourloaf.com/blog/2011/08/22/using-pattern-images-to-set-background-views.html">Using Pattern Images to Set Background Views</a>.</p>
<p>So, then we just make an new color with one of these initializers and store it in a variable, like so:</p>
<pre class="lang:swift decode:true">let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)</pre>
<p>There are a few things to note here.  First of all, what is alpha?  Alpha is simply a measurement of how opaque something is.  These colors can be made completely transparent with an alpha value of 0, or completely opaque with an alpha of 1.</p>
<p>Secondly, for those that particularly care about types, you will notice something odd.  CGFloat is similar to NSInteger, and even the Swift Integer type.  It is a different way of storing a floating point value that depends on the system it is running on.  On a 32-bit system a CGFloat is a typealias for a simple Float.  On a 64-bit system, a CGFloat is a typealias for a Double.  Here, you can clearly see that we have Swift Integers being used for these parameters and calculations.</p>
<p>I&#8217;m not entirely sure of the mechanisms here, but through testing I saw that you could use a Swift Double literal here ( so 1.0, 165.0/255.0, 0.0, 1.0) or the Integer literal form above and it accepted it.  I would guess that it has something to do with the type inference system.</p>
<p>However, Integer and Double are not actually toll-free bridged over.  If I make a separate variable and explicitly type it as a Swift Integer or Double type, it gives errors like &#8220;Cannot convert value of type &#8216;Int&#8217; to expected argument type &#8216;CGFloat&#8217;.&#8221;  If the variable is explicitly typed as a CGFloat, it will accept it.  You can make that variable explicitly typed as a CGFloat with either the literal &#8220;165/255&#8221; or &#8220;0.0/255.0&#8221;, so that is why I suspect it has something to do with inferring the typing, since the requirement of a CGFloat in that method gives the type system enough information to determine that it should interpret those literals as Floating point numbers.  It even tells it enough so that you don&#8217;t get the Integer division answer there, so:</p>
<pre class="lang:swift decode:true">let answer: CGFloat = 165/255

//The answer now stores the value "0.647058823529412".</pre>
<p>Instead of the integer division answer of 0 (since it is less than one, it just truncates the decimal component in Integer division).</p>
<h2>A handy extension</h2>
<p>How often do you make colors with less than 100% opacity?  If you don&#8217;t do so very often, perhaps you could make a convenience initializer that just assumes that the alpha value is 100%, and fills it in for you.</p>
<p>This sounds like a great place to use an extension.  The built in version is definitely the most versatile, but we can make our code easier to read by simply making an extension to UIColor that fills in some things for us.  In fact, it is probably more common to have RGB values than decimal percentages for each color, so let&#8217;s make this extension take Integers as parameters too.  This extension would then look like:</p>
<pre class="lang:swift decode:true">extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        let newRed = CGFloat(red)/255
        let newGreen = CGFloat(green)/255
        let newBlue = CGFloat(blue)/255
        
        self.init(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
    }
}</pre>
<p>We now have a much cleaner way of creating a UIColor.  After declaring this extension somewhere in your app&#8217;s module, you can do this:</p>
<pre class="lang:swift decode:true">//With the extension
let newSwiftColor = UIColor(red: 255, green: 165, blue: 0)</pre>
<p>One other cool thing to note, Swift&#8217;s Numeric Literal system can even accept literals in a few different bases, including hexadecimal itself!  That means, that with no other code on our part, you can actually put the hexadecimal numbers into this initializer as well, like so:</p>
<pre class="lang:swift decode:true">//With fancy Swift Numeric Literals
let fancySwiftColor = UIColor(red: 0xFF, green: 0xA5, blue: 0)</pre>
<p>You just have to prefix the numbers with the &#8220;0x&#8221; (just in case it is not clear, that is the number zero, followed by a lowercase letter &#8216;X&#8217;).</p>
<p>Pretty neat way to input color values to a UIColor, eh?</p>
<h2>Conclusion</h2>
<p>As a little bit of history, in Objective-C also used UIColor, but you had the choice of either creating colors with the initializers (like above) or via factory methods.  In the documentation for UIColor, both are shown, but only the initializers show a Swift implementation.  The basic difference between using one or the other was whether your class took ownership of the the UIColor created, or not.  Using an initializer, your class would take ownership, however if you used the factory method, it would not.  Since ARC (Automatic Reference Counting) was added, this distinction made little difference.  Beforehand though, if you used the initializer, you were responsible for decreasing the &#8220;retain count&#8221; of these colors, getting them one step closer to being dropped from memory when the system no longer needed them.</p>
<p>So the distinction was there, and rather important earlier on in Objective-C.  Then ARC came, and made these practically the same to most programmers.  Now with the introduction of Swift, they decided to go more to initializers than factory methods, and so decided to drop Swift support for them.  It&#8217;s interesting to see how these APIs evolve over time.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="UIColor Class Reference" href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/index.html">UIColor Class Reference —Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/create-uicolor-swift/">How to Create a UIColor in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Segue between Swift View Controllers</title>
		<link>https://www.codingexplorer.com/segue-swift-view-controllers/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 13 Jan 2015 14:30:07 +0000</pubDate>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Access Controls]]></category>
		<category><![CDATA[optionals]]></category>
		<category><![CDATA[properties]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=861</guid>

					<description><![CDATA[<p>So, last time we learned how to make a simple Hello World app on a single view controller.  As fancy as it was, you probably want more than one screen in your app, right? Perhaps you want a way to segue into the next screen? That&#8217;s what we&#8217;re going to go over today, as well as [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/segue-swift-view-controllers/">Segue between Swift View Controllers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="440" height="220" src="https://www.codingexplorer.com/wp-content/uploads/2015/01/SegueTitleSmall.png" class="rss-featured-image wp-post-image" alt="" align="" style="display:block;margin:10px auto;" decoding="async" loading="lazy" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/SegueTitleSmall.png 440w, https://www.codingexplorer.com/wp-content/uploads/2015/01/SegueTitleSmall-300x150.png 300w" sizes="auto, (max-width: 440px) 100vw, 440px" /><p>So, last time we learned how to make a simple Hello World app on a single view controller.  As fancy as it was, you probably want more than one screen in your app, right?</p>
<p>Perhaps you want a way to <em>segue</em> into the next screen?</p>
<p>That&#8217;s what we&#8217;re going to go over today, as well as one of the simple ways to share data between view controllers.<br />
<span id="more-861"></span></p>
<h2>Setting up the Storyboard</h2>
<p>So, first let&#8217;s make a new project.  We&#8217;ll call this one &#8220;SegueTutorial&#8221;.  If you need help setting up an Xcode project, please see the previous post <a title="Hello World! Your first iOS App in Swift" href="http://www.codingexplorer.com/hello-world-first-ios-app-swift/">&#8220;Hello World! Your first iOS App in Swift&#8221;</a>.</p>
<p>Unlike the last tutorial though, we&#8217;re not going to mess with Auto Layout here.  Let&#8217;s leave Auto Layout and Size Classes on, but I&#8217;m not going to cover where to pin or align things like I did last time.  If you want though, you are certainly welcome to set them yourself.  If you want to be lazy though, you can put any controls into the top left corner to make sure they will appear onscreen for an iPhone.  Of course don&#8217;t do that for an actual app after initial prototyping, but for now, let&#8217;s just look into how to use segues.</p>
<p>On our initial View Controller let&#8217;s drag out 2 buttons.  One is going to be used to generate some data for us, while the other one will send us to the other View Controller.  For the one to make data, change that one&#8217;s text to the numeral &#8220;0&#8221;.  We will click that one and increase its number each time.  When we go to the other view controller, we&#8217;ll send that number to the other view controller to display there.  We could use a textfield, but then we&#8217;d have to deal with hiding the keyboard when done, and that issue should probably have a post of its own.</p>
<p>For the other button, you can change it to whatever you want, but for the purposes of this tutorial, I suggest to name it verbosely:  &#8220;Go to Other View Controller&#8221;.</p>
<p>Next, from the Object library, drag out a &#8220;View Controller&#8221; object.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/01-ViewController.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-864" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/01-ViewController.png" alt="01-ViewController" width="237" height="207" /></a></p>
<p>When your cursor goes over the main editor area, the description will balloon up to show another big box similar to the one you already have in the editor.  Drop it somewhere to the right of your existing &#8220;View Controller&#8221;.</p>
<p>In this new View Controller, let&#8217;s put in a label.  The label will show the number generated in the previous view controller.  Change the text of the label to &#8220;The counter was tapped ??? times.&#8221;  This will make it easier to size it large enough to show at least a 3 digit number without having to make the label bigger.</p>
<h2>Wiring up the Segues</h2>
<p>Remember Ctrl+Dragging from <a title="Hello World! Your first iOS App in Swift" href="http://www.codingexplorer.com/hello-world-first-ios-app-swift/">last time</a>?  There we used it to make outlets and actions in our code.  Well, in addition to that, Ctrl+dragging also helps set up segues.  So, Ctrl+Drag from the &#8220;Go to Other View Controller&#8221; button, to somewhere in the second View Controller.  It can be anywhere in the main box of the second view controller.  When you release, it will show you a box like the one below.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/02-FirstSegue.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-865" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/02-FirstSegue.png" alt="02-FirstSegue" width="202" height="171" /></a></p>
<p>This lets you set what kind of segue you want to use.  I would recommend sticking with those in the &#8220;Action Segue&#8221; section.  They are new in iOS 8, and work better with the new Adaptive Layout than the deprecated ones below.  What do each of these mean?</p>
<ul>
<li>Show — When the View Controllers are in a UINavigationController, this pushes the next View Controller onto the navigation stack.  This allows the user to click the back button to return to the previous screen through the back button on the top left of the Navigation Bar.  Basically the adaptive form of &#8220;push&#8221;</li>
<li>Show detail — When the View Controllers are in a UISplitViewController, this will replace the detail view side of the UISplitView with the next View Controller.</li>
<li>Present modally — This presents the next view controller in a modal fashion over the current View Controller.  This one doesn&#8217;t need to be part of a UINavigationController or a UISplitViewController.  It just shows the destination View Controller in front of the previous one.  This is usually used when the user has to either Finish or Cancel what they are doing, where leaving partway through doesn&#8217;t make as much sense.  When you set up a new contact in the Contacts app, that is presented modally.  Leaving partway through doesn&#8217;t make sense, you are either creating a new contact or you are not.</li>
<li>Popover presentation — On an iPad, this shows the new View Controller over the previous one in a smaller box, usually with an arrow pointing to which button created the popover.  When used on an iPhone, it is not much different than the &#8220;Present Modally&#8221; segue by default, but can be configured to act more like an iPad one.</li>
<li>Custom — Exactly what it sounds like.  You can make your own segue style and transitions and use it here.  I have not dove into this yet, so I don&#8217;t know much more than that&#8230;. so far.</li>
</ul>
<p>For now, let&#8217;s use the &#8220;Show&#8221; segue.  Also, remember how I said that this one needs a UINavigation Controller?  Well, it doesn&#8217;t NEED one, it seems, running this as-is appears to show the sheet modally if there is no UINavigationController, but that&#8217;s not what we want in this tutorial, and isn&#8217;t really what &#8220;Show&#8221; is for.</p>
<p>Xcode makes it really easy to put these in a UINavigationController.  You could drag one out from the Object Library and wire it all up yourself&#8230;. or you can take a shortcut.</p>
<p>Highlight one of your first View Controller by clicking somewhere near the top of it (above the status bar, but not on the 3 icons in the center of the top.  Go to the top menu and click on Editor → Embed In → Navigation Controller.  This will wrap that current set of segues into a NavigationController, with all of the appropriate changes done for you.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/03-EmbedNavigation.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-867" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/03-EmbedNavigation.png" alt="03-EmbedNavigation" width="471" height="219" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/03-EmbedNavigation.png 471w, https://www.codingexplorer.com/wp-content/uploads/2015/01/03-EmbedNavigation-300x139.png 300w" sizes="auto, (max-width: 471px) 100vw, 471px" /></a></p>
<p>There is something that I kept messing up when I was learning this:  <strong>Make sure when you do this that <span style="text-decoration: underline;">only ONE</span> View Controller is selected</strong>.</p>
<p>I used to highlight the whole line that I wanted in the Navigation Controller, and it would show the Embed In → Navigation Controller option greyed out.  Only have the first View Controller in your Navigation stack selected when Embedding in a UINavigationController.</p>
<p>Also, if you when you do the embedding, a new Navigation Bar will appear and it might cover your buttons and labels if you are not using Auto Layout.  Simply highlight over them (even the one that is now blocked), and click and drag one that you can see.  For me, it covered the top one and some of the bottom one, so I could still drag from the part of the bottom one I could still see.   Just goes to show, you really should use Auto Layout.</p>
<p>Now, out first View Controller in the storyboard has a type already associated with it.  It is tied to the ViewController.swift file that was generated for us.  The new one however, is tied to a default UIViewController object provided by Cocoa.  If we want to be able to set that label, we need to be able to make an outlet to it in code.  For that, we need to create a new Swift file to make this View Controller that type.</p>
<p>So, go to &#8220;File → New → File&#8230;&#8221;, and and in the &#8220;iOS → Source&#8221; section, select &#8220;Cocoa Touch Class&#8221;.  Then in there call this Class &#8220;OtherViewController&#8221;, and make sure to set the &#8220;Subclass of&#8221; to &#8220;UIViewController&#8221;.  It will try to append this to what is type above, so I actually set the Subclass first, and then wrote &#8220;Other&#8221; before it.  It is good practice to have ViewController at the end of the names of your ViewController subclasses.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/04-OtherViewController.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-869" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/04-OtherViewController.png" alt="04-OtherViewController" width="708" height="414" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/04-OtherViewController.png 708w, https://www.codingexplorer.com/wp-content/uploads/2015/01/04-OtherViewController-300x175.png 300w" sizes="auto, (max-width: 708px) 100vw, 708px" /></a></p>
<p>You can leave the rest as default.  Don&#8217;t create a XIB, the &#8220;iPhone&#8221; combo box there is greyed out, so it doesn&#8217;t matter, and of course have your language set to Swift!  It will then ask you where to save this, so choose wherever you want.</p>
<p>Once done, it will show you the OtherViewController.swift file instead of the storyboard.  We aren&#8217;t QUITE done on the storyboard, so let&#8217;s go back and finish.  Select the second View Controller, and then go to the &#8220;Identity Inspector&#8221; in the Utility Pane.  It&#8217;s the icon that looks like a card with a picture in the top left corner and some writing everywhere else (it&#8217;s selected in blue in the screenshot below).  In there, set the &#8220;Class&#8221; part of the &#8220;Custom Class&#8221; section to our shiny new &#8220;OtherViewController.  If it is a compatible subclass (in this case of UIViewController), it will accept it.  It will also probably autocomplete once you start typing a compatible class.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/05-CustomClass.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-870" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/05-CustomClass.png" alt="05-CustomClass" width="256" height="99" /></a></p>
<p>Finally, click on the segue&#8217;s icon that is between the first and second view controller we made.  It is the circle on the arrow between our two View Controllers.  It actually looks different depending on which Segue is used.  Below is what our &#8220;Show&#8221; Segue looks like:</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/06-ShowSegue.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-871" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/06-ShowSegue.png" alt="06-ShowSegue" width="146" height="64" /></a></p>
<p>Once selected, in the Attributes Inspector of the Utilities pane, name the segue something in the &#8220;Identifier&#8221; text field.  Let&#8217;s name it &#8220;ShowCounterSegue&#8221; we will need to check for this later in the code.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/07-SegueIdentifier.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-872" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/07-SegueIdentifier.png" alt="07-SegueIdentifier" width="255" height="110" /></a></p>
<p>There, now the storyboard is ready for some code.</p>
<h2>Writing the View Controllers</h2>
<p>Now we&#8217;ll need a few things to access our labels and buttons in the code.  Close the utilities pane (to give some more room) and open up the Assistant Editor.</p>
<h3>ViewController.swift Part 1</h3>
<p>For our first View Controller, we need to wire up an action to our counter button, and nothing to our &#8220;Go to Other View Controller&#8221; button.  We don&#8217;t need anything for the second button, because the segue it is causing is the action we want.  We will be working with that segue soon enough.</p>
<p>Make sure you set it to be an &#8220;Action&#8221; and not an outlet.  Also, when doing this, you could set up an outlet to it as well to change the number on the button, but if you set this action&#8217;s sender &#8220;type&#8221; to be &#8220;UIButton&#8221; you can actually use a shortcut and assign right to the sender, being the button itself.  I messed up a few times writing this accidentally making it an outlet when I meant action though, so I&#8217;m just warning you.</p>
<p>If you do accidentally make an outlet you don&#8217;t want, make sure to remove the reference to that outlet on your button.  Only deleting the text is not enough.  You must Ctrl+Click (or right-click) on the button, and click the little X on the outlet in the &#8220;Referencing Outlets&#8221; section that no longer exists.  If you don&#8217;t, you get a nice error saying that it can&#8217;t find the code to tie the Outlet to (which was deleted).  Even undoing doesn&#8217;t remove this, so you do have to do this manually if you make the mistake, like me.</p>
<p>Anyway, also in the code, make a separate variable to hold the count, an integer that we will use to update the button&#8217;s text with.  In the action, simply increment the counter variable, and then assign the text of the button to that number.  You can use a String Initializer or String Interpolation to do this, the code below will use a  String Initializer.  If you are curious to learn more about Swift Strings, check out the previous post <a title="Swift Strings" href="http://www.codingexplorer.com/swift-strings/">Swift Strings</a>.  So the code added to ViewController.swift so far is:</p>
<pre class="lang:swift decode:true">var counter = 0

@IBAction func incrementCounter(_ sender: UIButton) {
    counter += 1

    sender.setTitle(String(counter), for: .normal)
}</pre>
<p>While writing this, I found setting the text of the titleLabel property is not particularly helpful.  It flashes the new number, but returns to zero.  You have to use this &#8220;setTitle:for:&#8221; method to correctly set the new text.  UIControlState.Normal is referring to the state that the button is in when it is not pressed, highlighted, etc.</p>
<h3>OtherViewController.swift</h3>
<p>Now, we need to set up another variable to store the number, and make an outlet for our &#8220;The counter was tapped ??? times.&#8221; label to show when we segue to this View Controller.  So Ctrl+Drag from the label to the assistant editor to make an outlet, and call it &#8220;counterLabel&#8221;.  Also make an Int variable named &#8220;numberToDisplay&#8221; with a default value of zero to store our count.</p>
<p>This &#8220;numberToDisplay&#8221; variable will be set from our first ViewController when segueing to this one to let us now what number to display.  If we were using access controls, this one should be marked as &#8220;internal&#8221;.  In the first ViewController.swift, that one should be private, since nothing should be setting it outside of itself.  For simplicity&#8217;s sake, we are forgoing access controls, but just so you know, while they are the same in this example, in a real app, you should probably have access controls to only expose things (with &#8220;internal&#8221; or &#8220;public&#8221;) that should be written to outside of your source file, otherwise have them marked as &#8220;private&#8221;.  You can read more about access controls in the post <a title="Access Control in Swift" href="http://www.codingexplorer.com/access-control-swift/">Access Control in Swift</a>.</p>
<p>Finally, we need to update this label somehow.  Well, ideally we want to update the text in this label right before the view will appear to the user.  To do that, we override the aptly named function &#8220;viewWillAppear&#8221;.  In there, we will update our label with the value in &#8220;numberToDisplay&#8221;.</p>
<p>So, with all of this, the code added to OtherViewController.swift is:</p>
<pre class="lang:swift decode:true">var numberToDisplay = 0

@IBOutlet var counterLabel: UILabel!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    counterLabel.text = "The counter was tapped \(numberToDisplay) times."
}</pre>
<p>The one part that wasn&#8217;t mentioned yet was the &#8220;super.viewWillAppear(animated)&#8221; line.  That line calls the viewWillAppear of its superclass (in this case UIViewController itself), in case it has anything it needs to do.  The &#8220;animated&#8221; argument is passing in the &#8220;animated&#8221; parameter that was given in the function&#8217;s prototype.</p>
<p>Now to finish the job, let&#8217;s head back to ViewController.swift.</p>
<h3>ViewController.swift Part 2</h3>
<p>You might have noticed a method commented out on the bottom of OtherViewController.swift called &#8220;prepareForSegue&#8221;.  The way we&#8217;re doing this, we don&#8217;t need that there, but we do need it in the main ViewController.swift.  In there we need to check which segue is being called first.  Then, if it is the correct segue, check if the destination view controller is the type we think it should be (in this case &#8220;OtherViewController&#8221;), and then set the numberToDisplay property in that object.</p>
<p>The code to do this is:</p>
<pre class="lang:swift decode:true">override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "ShowCounterSegue"
    {
        if let destinationVC = segue.destinationViewController as? OtherViewController {
            destinationVC.numberToDisplay = counter
        }
    }
}</pre>
<p>The default implementation of prepareForSegue does nothing, so you don&#8217;t need to call super.prepareForSegue.</p>
<p>Remember that we named this segue back in the storyboard?  The prepareForSegue method is called whenever ANY segue is called.  Since we have one, technically we don&#8217;t <em>have</em> to do this, but when more than one segue is possible, checking against that name is how you determine which one is happening, so you can prepare appropriately.  So first, we check if the identifier of the segue happening (with the segue.identifier property), is the one we think.  I&#8217;m not the biggest fan of Stringly Typing, and having to copy this String from our storyboard document, but currently it is the best way to handle it.  It might also be a good idea to create a constant to contain this String, so anywhere it is called in the code can use that constant.  In that case though, the constant and the storyboard&#8217;s segue identifier still have to be kept in sync.</p>
<p>Next, we optionally bind the result of trying to cast the segue.destinationViewController to a OtherViewController (with the optional as? operator).  If it is indeed able to be cast to OtherViewController (particularly because it IS one, in this case), then it can be referred to with destinationVC now.  If not, the if statement evaluates to false, and just finishes the method call (since nothing else is after it in an else clause or otherwise).</p>
<p>Once it is bound to destinationVC, we then set that numberToDisplay property we created back in OtherViewController.swift.</p>
<h2>Running the App</h2>
<p>With all of that, now we can run the app.  Click on the counter button a few times to set the number to something, then click the &#8220;Go to Other View Controller&#8221; button.  You will see it go to OtherViewController, with the correct number of times listed in the &#8220;The counter was tapped ??? times.&#8221; label.</p>
<p>To go back to the previous page, you can tap the back button generated for us in the UINavigationController&#8217;s UINavigationBar, in the top left.</p>
<p>We did take a bit of a shortcut for this app.  Since the first ViewController is kept on the stack, it remembers what the count is, and we aren&#8217;t changing it from the outside.  As such, we don&#8217;t need to update it&#8217;s label with viewWillAppear and an outlet to the button to set its text.  If it could be changed outside, we would have to override viewWillAppear in ViewController.swift as well.</p>
<p>For completion&#8217;s sake, here is all of the new code in:</p>
<p>ViewController.swift:</p>
<pre class="lang:swift decode:true">import UIKit

class ViewController: UIViewController {

    var counter = 0
    
    @IBAction func incrementCounter(_ sender: UIButton) {
        counter += 1
        
        sender.setTitle(String(counter), for: .normal)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ShowCounterSegue",
            let destinationVC = segue.destination as? OtherViewController {
                destinationVC.numberToDisplay = counter
        }
    }
}</pre>
<p>OtherViewController.swift</p>
<pre class="lang:swift decode:true ">import UIKit

class OtherViewController: UIViewController {
    
    var numberToDisplay = 0
    
    @IBOutlet var counterLabel: UILabel!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        counterLabel.text = "The counter was tapped \(numberToDisplay) times."
    }
}</pre>
<h2>Conclusion</h2>
<p><strong><strong>Screenshots taken from <strong>Xcode 6.1.1, code checked against version listed at top of the post.</strong></strong></strong></p>
<p>Segues are a very important part of using Storyboards in Xcode.  We can go over the different types of segues another time, but this one shows you how to use the &#8220;Show&#8221; segue, as well as how to pass data between the two view controllers to customize the second one with whatever custom data is required.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="cocoa touch - Text change on UIButton doesn't stick - Stack Overflow" href="http://stackoverflow.com/a/5579515/2775523">Text change on UIButton doesn&#8217;t stick — Stack Overflow</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/segue-swift-view-controllers/">Segue between Swift View Controllers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Hello World! Your first iOS App in Swift</title>
		<link>https://www.codingexplorer.com/hello-world-first-ios-app-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 06 Jan 2015 14:31:43 +0000</pubDate>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=820</guid>

					<description><![CDATA[<p>So far we&#8217;ve covered a lot of how Swift the language works, some WatchKit tutorials, and how to get started with some Cocoa classes.  However, we have not really done much in the way of actually writing sample apps on the Coding Explorer Blog.  It was covered a little bit in the WatchKit tutorials, but [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/hello-world-first-ios-app-swift/">Hello World! Your first iOS App in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So far we&#8217;ve covered a lot of how Swift the language works, some WatchKit tutorials, and how to get started with some Cocoa classes.  However, we have not really done much in the way of actually writing sample apps on the Coding Explorer Blog.  It was covered a little bit in the WatchKit tutorials, but there is a lot done there specific to getting WatchKit working.  Let&#8217;s go all the way back to the basics, let&#8217;s write a Hello World app.</p>
<p>For those that don&#8217;t know, it is very common to have the first program written by somebody learning a new language be one that somehow displays &#8220;Hello World!&#8221;  At least according to <a title="&quot;Hello, world!&quot; program - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/%22Hello,_world!%22_program">Wikipedia</a>, this goes back to an example from &#8220;The C Programming Language&#8221; book by Brian Kernighan and Dennis Ritchie.  Now, of course the simplest form of this in Swift is just:</p>
<pre class="lang:swift decode:true">print("Hello, World!")</pre>
<p>But we&#8217;ll do something a bit more advanced than that.  You don&#8217;t often (or ever) see a console on your iOS device, so that doesn&#8217;t help us make an app directly.</p>
<p>This is a pretty basic tutorial, but I want to make it pretty comprehensive for how to start an iOS app.  This will even include going over some of the features of the IDE (integrated Development Environment), like the different editors, the utility pane, and the various inspectors therein.  This may be a bit too basic for some, but I want this site to be a place for all kinds of iOS developers, especially the beginners.  We all had to start sometime, and those are the people I want to help in particular today.</p>
<p>Also, I figured that it&#8217;s a new year, let&#8217;s start it with how to start a new app.<br />
<span id="more-820"></span></p>
<h2>Creating the Hello World iOS App Project</h2>
<p>So, when you first load Xcode, assuming you haven&#8217;t turned it off in the preferences, you will see the &#8220;Welcome to Xcode&#8221; screen.  To start a new app, you click the appropriately titled &#8220;Create a new Xcode project&#8221; button.  If you have hidden this page, or prefer using menus, you can create a new project via &#8220;File → New → Project&#8230;&#8221;.</p>
<p>After you click that, you are shown the template screen.  You have many choices built in here, which will start you off with an Xcode project that is preconfigured as whichever one you select.  For us though, let&#8217;s choose the simplest one, the &#8220;Single View Application&#8221;.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/01-Templates.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-822" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/01-Templates.png" alt="01-Templates" width="728" height="424" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/01-Templates.png 728w, https://www.codingexplorer.com/wp-content/uploads/2015/01/01-Templates-300x175.png 300w" sizes="auto, (max-width: 728px) 100vw, 728px" /></a></p>
<p>Next, you are presented with the page to set many of the important aspects of your project, particularly your &#8220;Product Name&#8221; and &#8220;Language&#8221;, which will be Swift, of course.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/02-Options.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-825" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/02-Options.png" alt="02-Options" width="705" height="415" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/02-Options.png 705w, https://www.codingexplorer.com/wp-content/uploads/2015/01/02-Options-300x177.png 300w" sizes="auto, (max-width: 705px) 100vw, 705px" /></a></p>
<p>Product Name is pretty self-explanatory.  The organization name can be whatever you want, but it probably should the the company or name you are releasing your apps under.</p>
<p>The Organization Identifier is part of how your app will be referred to a bit more internally.  It is customary to use a reverse domain name of your company as the Organization identifier, so in my case my normal URL of &#8220;www.codingexplorer.com&#8221; should become &#8220;com.codingexplorer&#8221;.  You can see below it that the &#8220;Bundle Identifier&#8221; is created based on the product name and the organization identifier.  This is part of how your iOS device determines whether an update to your app is the same app or a new one, by checking this Bundle Identifier.</p>
<p>The Language box gives you the choice of Objective-C or Swift.  Of course for this blog, we&#8217;ll be choosing Swift for this box.  The next box has you select what devices this app should run on.  You have the choice of iPhone, iPad, or Universal.  Apple is heading more in the way of universal apps, so we&#8217;ll go with that for now (though this app will be designed for an iPhone, so it will look a bit silly on an iPad).  Finally you can click that checkbox if you want Xcode to get some Core Data code ready for you.  I don&#8217;t know enough about Core Data yet to really recommend whether or not to use this checkbox when using core data.  It would probably be best in the beginning at least not to, if only to let you see all of the moving parts of Core Data by having to set them up yourself.  After you learn though, I don&#8217;t know if it is better than doing it yourself or not.</p>
<p>As of Xcode 7.3, there are also 2 more checkboxes at the bottom, &#8220;Include Unit Tests&#8221; and &#8220;Include UI Tests&#8221;.  The first one creates a separate target that you can write tests for your main app&#8217;s code in.  The second is used with Xcode7&#8217;s new ability to run tests on a UI, as opposed to calling code directly.  For this app, we will leave these unselected.</p>
<p>When you click next, you will be presented with a save dialog, asking where you want to save your project.  Wherever you save it, a folder will be created with your app&#8217;s name, and inside will be the Xcode project, and a folder for each target your app has (which is going to be the app itself, and a test target right now).  You also have the option to create a Git repository for your project either locally or on a server.</p>
<p>After you click the &#8220;Create&#8221; button, the files for your project are generated and you are probably looking at your AppDelegate.swift file.</p>
<h2>Setting up the Storyboard</h2>
<p>Now we&#8217;ll set up the storyboard.  This app will present the user with a UILabel and a UIButton.  When the UIButton is tapped, &#8220;Hello World!&#8221; will show up in the UILabel.</p>
<p>Make sure that you are showing the Utility Pane on the right side.  The shortcut for this is the box with a thick vertical line on the right side, which should be in the top right of your editor (and of the screenshot below).  With that open, on the bottom of the Utility pane, make sure you have the Object Library shown, which is done by having the buttons selected that looks like the original iPhone home button (a circle with a square in it).  This is also shown in the screenshot below.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/03-ObjectLibrary.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-827" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/03-ObjectLibrary.png" alt="03-ObjectLibrary" width="253" height="387" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/03-ObjectLibrary.png 253w, https://www.codingexplorer.com/wp-content/uploads/2015/01/03-ObjectLibrary-196x300.png 196w" sizes="auto, (max-width: 253px) 100vw, 253px" /></a></p>
<p>Inside the Object Library, we will drag out a UILabel and a UIButton onto the storyboard.  You can scroll through it, but I prefer to search using the search bar at the very bottom of the Utility Pane.  Once you find the object in the list, you click and drag it out.  Hold your cursor wherever you want to put the object on the ViewController, and then release the mouse button.</p>
<p>Let&#8217;s have these two objects be horizontally centered.  Place them roughly where you want them to be using the guidelines the Xcode shows when you are near the margins or center.  Don&#8217;t worry about being exact, we&#8217;ll get to that later.</p>
<p>You can customize what the label and Button to say by simply double clicking on them.  That will put them into edit mode with a cursor showing, and you can type in what you want there.  Let&#8217;s change the label to say &#8220;App is now loaded&#8230;&#8221; and the button to say &#8220;Say Something&#8221;.  After filling in these, you might need to recenter them, since it leaves their left edge wherever it was when you started loading.  You could also wait and have Xcode do it for you when we do one of the next steps.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/04-TextCustomized.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-828" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/04-TextCustomized.png" alt="Initial layout with Text Customized" width="608" height="640" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/04-TextCustomized.png 608w, https://www.codingexplorer.com/wp-content/uploads/2015/01/04-TextCustomized-285x300.png 285w" sizes="auto, (max-width: 608px) 100vw, 608px" /></a></p>
<h3>Set Object Locations with Auto Layout</h3>
<p>We&#8217;re going to use size-classes and Auto Layout in this app to make it universal, so we&#8217;ll need to set up someAuto Layout constraints.  Don&#8217;t worry, it&#8217;s pretty easy for this app.  We won&#8217;t specialize size-classes for Compact vs Regular for now though, so it will look a bit silly on an iPad.</p>
<p>Select the &#8220;App is now loaded&#8230;&#8221; label, and click on the Pin button in the bottom right of the editor area.  The &#8220;Pin&#8221; button is what the popover is pointing to in the screenshot below.  If it is not aligned to the top guide, set the top constraint to 8.  If it is already, make sure to click the dotted red &#8220;I&#8221; shape between the top constraint box, and the reference box in the middle to make the dotted lines solid red.  We&#8217;ll set the left and right constraints to 0, and the bottom one to 50.</p>
<p>Doing all this will make constraints that tell the label to be snug to the left and right margin, 8 points from the top margin, and 50 away from the nearest neighbor below it (being the button in this case).</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/05-UILabelPin.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-833" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/05-UILabelPin.png" alt="Pin top: 8, left/right: 0, and buttom: 50. Update Frames to Items of New Constraints" width="255" height="400" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/05-UILabelPin.png 255w, https://www.codingexplorer.com/wp-content/uploads/2015/01/05-UILabelPin-191x300.png 191w" sizes="auto, (max-width: 255px) 100vw, 255px" /></a></p>
<p>We&#8217;ll also change the &#8220;Update Frames&#8221; option to &#8220;Items of New Constraints&#8221;.  This will update the label&#8217;s actual location on the storyboard to be in accordance with the new constraints.  Since we have the bottom constraint to the button, it will also move the button to be 50 away from the label.  At the moment it also moves it to the far left like the label, but that&#8217;s more because it doesn&#8217;t know what to do horizontally yet with it.  That&#8217;s the next step.</p>
<p>We want the button to be in the center, so let&#8217;s set that.  Select the button and click the &#8220;align icon&#8221; in the bottom right area of the editor area.  It&#8217;s just to the left of the &#8220;Pin&#8221; icon, and also shown in the screenshot below.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/06r-ButtonAlign.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-835" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/06r-ButtonAlign.png" alt="Horizontal Center and Update Frames to Items of New Constraints" width="295" height="320" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/06r-ButtonAlign.png 295w, https://www.codingexplorer.com/wp-content/uploads/2015/01/06r-ButtonAlign-277x300.png 277w" sizes="auto, (max-width: 295px) 100vw, 295px" /></a></p>
<p>There we&#8217;ll only enable the &#8220;Horizontal Center in Container&#8221; checkbox, and leave its constant at 0.  This will set the center of the button to the center of the container itself.  Again we&#8217;ll also update the frames for items of new constraints.  When you click the &#8220;Add 1 Constraint&#8221; button it will move to the center as we requested.  If you leave the &#8220;Update Frames&#8221; box to its default, they won&#8217;t move, but show some auto-layout warnings telling you to move it yourself.</p>
<p>At this point you&#8217;ll see that the UIButton is centered, and while the UILabel itself is effectively (since it is pinned equally to each side) centered, the text in it is not.</p>
<p>We pinned the label to the sides because the we want the label to be big enough when we put different text in.  The label won&#8217;t automatically resize to fit its content.</p>
<p>Now to align the text itself, click on the UILabel, and in Attributes Inspector in the Utility Pane.  The attributes inspector is that icon that is an arrow pointing down along a line (the blue one near the center of the screenshot below), kind of like a slider on some systems.  In there, click on the center text alignment button, which looks like a text alignment button in Pages or Word.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/07r-UILabelAlignment.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-836" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/07r-UILabelAlignment.png" alt="Center UILabel Text Alignment" width="240" height="225" /></a></p>
<p>Now that we&#8217;ve done that, we have everything centered and ready for the code.</p>
<h2>Customizing ViewController.swift</h2>
<p>Now we need to wire up the UILabel and the UIButton to be accessible in the code.  We&#8217;ll need to wire up an outlet to the UILabel, and an action to the UIButton.</p>
<p>The easiest way is with the assistant editor.  You can open the assistant editor with the icon that has two intersecting circles on it.  While we&#8217;re there, we might as well turn off the Utility Pane to get a bit more room for the assistant editor, since we are done with it now.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/08r-AssistantEditor.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-837" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/08r-AssistantEditor.png" alt="Opening the Assistant Editor" width="420" height="60" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/08r-AssistantEditor.png 420w, https://www.codingexplorer.com/wp-content/uploads/2015/01/08r-AssistantEditor-300x43.png 300w" sizes="auto, (max-width: 420px) 100vw, 420px" /></a></p>
<p>There you will see that it will (by default) open something in a window on the right that is associated to what is in the main editor window on the left.  In the case of our storyboard, it will open up the ViewController that goes along with it, which was named by default ViewController.swift.</p>
<p>With the assistant editor, we can make these by dragging from the main editor, to where you want the code to appear in the ViewController.swift file.  This can be done a few ways.  If you have a two (or more) button mouse, you can simply do it by dragging with a right click.  This is my preferred method.  If you have only 1 button (or a trackpad), you can do this by Control dragging what that single button (or the left button if using a 2+ button mouse for this way.  Either way, when you release the drag on the code, it will present you with a window to set the settings for your outlet or action.  I will refer to the dragging as Ctrl+Drag in the rest of this tutorial, despite that I prefer right-click dragging.</p>
<p>So Ctrl+Drag from your UILabel to where you want the outlet to go in the code.  This will open a window like the one below.  Make sure the &#8220;Connection&#8221; says &#8220;Outlet&#8221;.  Then give it a name, for this tutorial, let&#8217;s name it &#8220;displayLabel&#8221;.  The other two can stay as their defaults.  Click the &#8220;Connect&#8221; button and it will create the code for the outlet.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/09r-LabelOutlet.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-838" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/09r-LabelOutlet.png" alt="09r-LabelOutlet" width="315" height="140" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/09r-LabelOutlet.png 315w, https://www.codingexplorer.com/wp-content/uploads/2015/01/09r-LabelOutlet-300x133.png 300w" sizes="auto, (max-width: 315px) 100vw, 315px" /></a></p>
<p>Since this screenshot was originally taken, it has been suggested by Apple to set your Storage type to &#8220;Strong&#8221;, instead of &#8220;weak&#8221; as is shown in this screenshot.</p>
<p>You can check out <a href="https://developer.apple.com/videos/play/wwdc2015/407/?time=1946">WWDC 2015 — Session 407 — Implementing UI Designs in Interface Builder</a>, which also shows some great information about how to use Interface Builder.  The link is even timestamped to go to the part about the Storage type specifically, neat!</p>
<p>Next, Ctrl+Drag from your UIButton into the code to get a similar box.  However for this one, make sure you set the &#8220;Connection&#8221; to be an &#8220;Action&#8221;.  Once you set that, the options available in the box will change.  The name is still there though, so we&#8217;ll name it &#8220;saySomethingTapped&#8221;.</p>
<p>Next is the &#8220;Type option.  When the action is created, it will usually have a parameter named &#8220;sender&#8221;.  It will be of the type specified in this &#8220;Type&#8221; option.  By default it is set to be an &#8220;AnyObject&#8221;.  If you do something with the sender that is dependent on type, setting it here makes it so you won&#8217;t have to type cast it later.  Even if I didn&#8217;t have to use it though, I usually set it to be the type that it should be.  I don&#8217;t know if this adds significant overhead, but this is my preference unless I hear a good reason not to.  For now, let&#8217;s set it to be the appropriate &#8220;UIButton&#8221;.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/10r-UIButtonAction.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-839" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/10r-UIButtonAction.png" alt="10r-UIButtonAction" width="315" height="160" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/10r-UIButtonAction.png 315w, https://www.codingexplorer.com/wp-content/uploads/2015/01/10r-UIButtonAction-300x152.png 300w" sizes="auto, (max-width: 315px) 100vw, 315px" /></a></p>
<p>Then you can set which event to trigger this auction method on.  The default is &#8220;Touch Up Inside&#8221;, meaning that once you lift your finger, as long as it is still inside the button, this will trigger.  There are many different options, but this is the most common, and what you will probably usually do.</p>
<p>The final option is the &#8220;Arguments&#8221; option.  By default, the parameter included is the &#8220;Sender&#8221;, as mentioned earlier.  You can set it to have no arguments, or even set it to show the event that caused it too.  For now, let&#8217;s leave it as the &#8220;Sender&#8221; option.</p>
<p>Click the &#8220;Connect&#8221; button and your action method will be written in the code.  Now, like any other method, you write what should happen when this method is called inside.  Despite all of this setup, the code will be pretty simple.</p>
<p>The UILabel class has a property just called &#8220;text&#8221; that takes or returns a String (technically an NSString) of the text for the UILabel.  So we will set it to the String &#8220;Hello World!&#8221;, like in the code below.</p>
<pre class="lang:swift decode:true">@IBAction func saySomethingTapped(_ sender: UIButton) {
    displayLabel.text = "Hello World!"
}</pre>
<p>That&#8217;s it!</p>
<p>Just for completeness sake, here is all of the code in the ViewController.swift file:</p>
<pre class="lang:swift decode:true">import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var displayLabel: UILabel!

    @IBAction func saySomethingTapped(_ sender: UIButton) {
        displayLabel.text = "Hello World!"
    }
}</pre>
<p>This does include some of the original boilerplate that it was created with.  I wanted to make this app as simple as possible, so we didn&#8217;t remove some of the boilerplate we don&#8217;t really need for this app.</p>
<h2>Running the App</h2>
<p>So now you run the app with the big &#8220;Play&#8221; button in the top left of Xcode.  You then need to set what device to run the app on.  You can select a physical device (if you have a paid developer license).  Otherwise, or even just for simpler testing, you can run it in the simulator.  Choose the simulated device to run it on from the same menu.</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/11r-SelectScheme.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-840" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/11r-SelectScheme.png" alt="11r-SelectScheme" width="365" height="30" srcset="https://www.codingexplorer.com/wp-content/uploads/2015/01/11r-SelectScheme.png 365w, https://www.codingexplorer.com/wp-content/uploads/2015/01/11r-SelectScheme-300x25.png 300w" sizes="auto, (max-width: 365px) 100vw, 365px" /></a></p>
<p>Then wait a bit while the simulator loads.  Mine took about 30 seconds to load.  Then click the button in your app, and watch it change the text in the label!</p>
<p><a href="http://www.codingexplorer.com/wp-content/uploads/2015/01/12r-Clicking.gif"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-841" src="http://www.codingexplorer.com/wp-content/uploads/2015/01/12r-Clicking.gif" alt="12r-Clicking" width="338" height="608" /></a></p>
<h2>Conclusion</h2>
<p><strong>Screenshots taken from Xcode 6.1.1, code checked against version listed at top of the post.</strong></p>
<p>While this was a simple app, the post got up to at least 2,700 words.  I wanted this to be pretty comprehensive for the beginners, so that I wouldn&#8217;t assume anything, even that people would know what the different panes or inspectors were called.  Don&#8217;t worry, most tutorials won&#8217;t have THAT much detail in them.  Now in future tutorials, readers can be directed back to this one for a lot of the early setup stuff if they need it.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/hello-world-first-ios-app-swift/">Hello World! Your first iOS App in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swiftly getting a human-readable date with NSDateFormatter</title>
		<link>https://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 22 Dec 2014 14:30:14 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=768</guid>

					<description><![CDATA[<p>Now that we know a bit about Date and DateComponents, let&#8217;s actually get a readable date in our Swift app, shall we?  This is the job of DateFormatter.  DateFormatter is a class that can take a Date, and output a String describing that time/date as its format instructions dictate.  In other words, you tell it [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/">Swiftly getting a human-readable date with NSDateFormatter</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Now that we know a bit about <a title="Date — Class Reference" href="http://www.codingexplorer.com/nsdate-class-reference/">Date</a> and <a title="DateComponents — Class Reference" href="http://www.codingexplorer.com/nsdatecomponents-class-reference/">DateComponents</a>, let&#8217;s actually get a readable date in our Swift app, shall we?  This is the job of DateFormatter.  DateFormatter is a class that can take a Date, and output a String describing that time/date as its format instructions dictate.  In other words, you tell it what you want to know, and it will give you a String that says that.  It has a few pretty useful built-in formats, and the capability to accept a custom date format string.</p>
<p>There&#8217;s not too much to the actual creation of an DateFormatter object.  It pretty much just has an empty initializer (and an NSCoding one, but we aren&#8217;t covering NSCoding today).  After initializing your DateFormatter, you set the appropriate style for the date and time, and that&#8217;s all you need.<br />
<span id="more-768"></span></p>
<h2>Built-In DateFormatter.Style Values</h2>
<p>As mentioned earlier, there are some built in formats used for date and time.  Both the dateStyle and timeStyle properties take a value from the DateFormatter.Style enumeration.  They interpret the enumeration differently, but they are expressive enough to be shared between them.  Below is an example of what the various DateFormatter.Styles do for their respective output.  These examples are for an en-US locale:</p>
<table border="1">
<tbody>
<tr>
<td style="padding: 5px;"><strong>DateFormatter.Style</strong></td>
<td style="padding: 5px;"><strong>Date Out</strong></td>
<td style="padding: 5px;"><strong>Time Out</strong></td>
</tr>
<tr>
<td style="padding: 5px;">ShortStyle</td>
<td style="padding: 5px;">12/25/19</td>
<td style="padding: 5px;">7:00 AM</td>
</tr>
<tr>
<td style="padding: 5px;">MediumStyle</td>
<td style="padding: 5px;">Dec 25, 2019</td>
<td style="padding: 5px;">7:00:00 AM&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">LongStyle</td>
<td style="padding: 5px;">December 25, 2019</td>
<td style="padding: 5px;">7:00:00 AM PST</td>
</tr>
<tr>
<td style="padding: 5px;">FullStyle</td>
<td style="padding: 5px;">Wednesday, December 25, 2014</td>
<td style="padding: 5px;">7:00:00 AM Pacific Standard Time</td>
</tr>
</tbody>
</table>
<p>Here&#8217;s a bit of sample code to create the above Date (using DateComponents, which you can read about in the previous post <a title="DateComponents — Class Reference" href="http://www.codingexplorer.com/nsdatecomponents-class-reference/">DateComponents — Class Reference</a>), and then using DateFormatter in Swift:</p>
<pre class="lang:swift decode:true">let morningOfChristmasComponents = DateComponents(calendar: Calendar.current,
                                                  year: 2019,
                                                  month: 12,
                                                  day: 25,
                                                  hour: 7,
                                                  minute: 0,
                                                  second: 0)

let morningOfChristmas = morningOfChristmasComponents.date!

/***** DateFormatter Part *****/
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .medium

let dateString = formatter.string(from: morningOfChristmas)
//dateString now contains the string:
//"December 25, 2019 at 7:00:00 AM"</pre>
<p>As you can see, you can set the dateStyle and timeStyle as different values.  Also, like every use of enumerations in Swift, you can also use type inference and not write the enumeration&#8217;s name each time if the property it is set to is already typed as that enum.  After that, you just call the stringFromDate instance method of the DateFormatter object you created, giving the date you want it to format as an argument, and it will return a String containing that date in a human-readable format the way you told it to.</p>
<h2>Custom Fixed DateFormatter Styles</h2>
<p>To be honest, I&#8217;ve pretty much only used the built-in DateFormatter.Styles in what I&#8217;ve worked on, they did what I needed.  However, if you do want to do something different, you can write your own custom format string.  This string will be a series of characters that DateFormatter knows are stand-ins for the values you want to show, and then replace them with the appropriate values.</p>
<p>The character patterns used in these format strings are based on the Unicode Technical Standard #35.  Apple&#8217;s documentation for date formatting strings (available at <a title="Data Formatting Guide: Date Formatters" href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW13">Data Formatting Guide: Date Formatters</a>) lists which revision of the standard is used for each iOS and OS X version up to OS X 10.9 and iOS 7.  This has still not been updated to any later versions of the Operating systems, so I&#8217;m going to assume for now that it still is working with tr35-31.</p>
<p>As a side note, it would APPEAR that they are using at least revision 35.  After some sleuthing, it responds correctly to the &#8220;r&#8221; formatter, which did not appear until revision 35.  I don&#8217;t think there is <em>much</em> different for the Gregorian calendar though, so for now, I will write this assuming they are still using revision 31 at <a title="UTS #35: Unicode LDML: Dates" href="http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns">tr35-31</a>.</p>
<p>So, basically, if you wanted to say something like, &#8220;Wednesday, 7 AM&#8221;, you would do something like this:</p>
<pre class="lang:swift decode:true">let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "EEEE, h a"

let smallDateString = dayTimePeriodFormatter.string(from:morningOfChristmas)
//smallDateString now contains the string "Wednesday, 7 AM".</pre>
<p>Below I have included a chart of what I think will be the most useful date field symbols.  These are written from the perspective of an &#8220;en-US&#8221; locale with the Gregorian calendar.  If you want to see the full list, you can see it at the <a title="UTS #35: Unicode LDML: Dates" href="http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Field_Symbol_Table">UTS #35-31: Unicode LDML: Dates</a>.</p>
<table border="1">
<tbody>
<tr>
<td style="padding: 5px;"><strong>Format</strong></td>
<td style="padding: 5px;"><strong>Description</strong></td>
<td style="padding: 5px;"><strong>Example</strong></td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;y&#8221;</td>
<td style="padding: 5px;">A <strong>year</strong> with at least 1 digit.</td>
<td style="padding: 5px;">
<p>1 AD →        &#8220;1&#8221;</p>
<p>42 AD →     &#8220;42&#8221;</p>
<p>2014 AD → &#8220;2014&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;yy&#8221;</td>
<td style="padding: 5px;">
<p>A <strong>year</strong> with <strong>exactly</strong> 2 digits.</p>
<p>If less, it is padded with a zero.</p>
<p>It will be truncated to the tens digit if larger.</td>
<td style="padding: 5px;">
<p>1 AD → &#8220;01&#8221;</p>
<p>42 AD → &#8220;42&#8221;</p>
<p>2014 AD → &#8220;14&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;yyy&#8221;</td>
<td style="padding: 5px;">
<p>A <strong>year</strong> with at least 3 digits.</p>
<p>If less, it is padded with zeros.</td>
<td style="padding: 5px;">
<p>1 AD →  &#8220;001&#8221;</p>
<p>42 AD →  &#8220;042&#8221;</p>
<p>2014 AD → &#8220;2014&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;yyyy&#8221;</td>
<td style="padding: 5px;">
<p>A <strong>year</strong> with at least 3 digits.</p>
<p>If less, it is padded with zeros.</td>
<td style="padding: 5px;">
<p>1 AD → &#8220;0001&#8221;</p>
<p>42 AD → &#8220;0042&#8221;</p>
<p>2014 AD → &#8220;2014&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;M&#8221;</td>
<td style="padding: 5px;">A <strong>month</strong> with at least 1 digit.</td>
<td style="padding: 5px;">
<p>July → &#8220;7&#8221;</p>
<p>December → &#8220;12&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;MM&#8221;</td>
<td style="padding: 5px;">
<p>A <strong>month</strong> with at least 2 digits.</p>
<p>If less, it is padded with zeros.</td>
<td style="padding: 5px;">
<p>July → &#8220;07&#8221;</p>
<p>December → &#8220;12&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;MMM&#8221;</td>
<td style="padding: 5px;">Three letter <strong>month</strong> abbreviation.</td>
<td style="padding: 5px;">
<p>July → &#8220;Jul&#8221;</p>
<p>December → &#8220;Dec&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;MMMM&#8221;</td>
<td style="padding: 5px;">Full name of <strong>month</strong>.</td>
<td style="padding: 5px;">
<p>July → &#8220;July&#8221;</p>
<p>December → &#8220;December&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;MMMMM&#8221;</td>
<td style="padding: 5px;">
<p>One letter <strong>month</strong> abbreviation.</p>
<p>Not unique, January, June, and July are all &#8220;J&#8221;.</td>
<td style="padding: 5px;">
<p>July → &#8220;J&#8221;</p>
<p>December → &#8220;D&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;d&#8221;</td>
<td style="padding: 5px;">A <strong>day</strong> with at least 1 digit.</td>
<td style="padding: 5px;">
<p>4 → &#8220;4&#8221;</p>
<p>25 → &#8220;25&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;dd&#8221;</td>
<td style="padding: 5px;">
<p>A <strong>day</strong> with at least 2 digits.</p>
<p>If less, it is padded with a zero.</td>
<td style="padding: 5px;">
<p>4 → &#8220;04&#8221;</p>
<p>25 → &#8220;25&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;E&#8221;, &#8220;EE&#8221;, or&#8221;EEE&#8221;</td>
<td style="padding: 5px;">3 letter day abbreviation of <strong>day name</strong>.</td>
<td style="padding: 5px;">
<p>Wednesday → &#8220;Wed&#8221;</p>
<p>Thursday → &#8220;Thu&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;EEEE&#8221;</td>
<td style="padding: 5px;">Full <strong>day name</strong>.</td>
<td style="padding: 5px;">
<p>Wednesday → &#8220;Wednesday&#8221;</p>
<p>Thursday → &#8220;Thursday&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;EEEEE&#8221;</td>
<td style="padding: 5px;">
<p>1 letter day abbreviation of <strong>day name</strong>.</p>
<p>Not unique, Tuesday and Thursday are both &#8220;T&#8221;.</td>
<td style="padding: 5px;">
<p>Wednesday → &#8220;W&#8221;</p>
<p>Thursday → &#8220;T&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;EEEEEE&#8221;</td>
<td style="padding: 5px;">2 letter day abbreviation of <strong>day name</strong>.</td>
<td style="padding: 5px;">
<p>Wednesday → &#8220;We&#8221;</p>
<p>Thursday → &#8220;Th&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;a&#8221;</td>
<td style="padding: 5px;">Period of day (AM/PM).</td>
<td style="padding: 5px;">
<p>5 PM → &#8220;PM&#8221;</p>
<p>7 AM → &#8220;AM&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;h&#8221;</td>
<td style="padding: 5px;">A 1-12 based <strong>hour</strong> with at least 1 digit.</td>
<td style="padding: 5px;">
<p>5 PM → &#8220;5&#8221;</p>
<p>7 AM → &#8220;7&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;hh&#8221;</td>
<td style="padding: 5px;">
<p>A 1-12 based <strong>hour</strong> with at least 2 digits.</p>
<p>If less, it is padded with a zero.</td>
<td style="padding: 5px;">
<p>5 PM → &#8220;05&#8221;</p>
<p>7 AM → &#8220;07&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;H&#8221;</td>
<td style="padding: 5px;">A 0-23 based <strong>hour</strong> with at least 1 digit.</td>
<td style="padding: 5px;">
<p>5 PM → &#8220;17&#8221;</p>
<p>7 AM → &#8220;7&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;HH&#8221;</td>
<td style="padding: 5px;">
<p>A 0-23 based <strong>hour</strong> with at least 2 digits.</p>
<p>If less, it is padded with a zero.</td>
<td style="padding: 5px;">
<p>5 PM → &#8220;17&#8221;</p>
<p>7 AM → &#8220;07&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;m&#8221;</td>
<td style="padding: 5px;">A <strong>minute</strong> with at least 1 digit.</td>
<td style="padding: 5px;">
<p>40 → &#8220;40&#8221;</p>
<p>1 → &#8220;1&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;mm&#8221;</td>
<td style="padding: 5px;">
<p>A <strong>minute</strong> with at least 2 digits.</p>
<p>If less, it is padded with a zero.</td>
<td style="padding: 5px;">
<p>40 → &#8220;40&#8221;</p>
<p>1 → &#8220;01&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;s&#8221;</td>
<td style="padding: 5px;">A <strong>second</strong> with at least 1 digit.</td>
<td style="padding: 5px;">
<p>40 → &#8220;40&#8221;</p>
<p>1 → &#8220;1&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;ss&#8221;</td>
<td style="padding: 5px;">
<p>A <strong>second</strong> with at least 2 digits.</p>
<p>If less, it is padded with a zero.</td>
<td style="padding: 5px;">
<p>40 → &#8220;40&#8221;</p>
<p>1 → &#8220;01&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;S&#8221;</td>
<td style="padding: 5px;">Tenths place of <strong>fractional second</strong>.</td>
<td style="padding: 5px;">
<p>123 ms → &#8220;1&#8221;</p>
<p>7 ms → &#8220;0&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;SS&#8221;</td>
<td style="padding: 5px;">
<p>Tenths and hundredths</p>
<p>place of a <strong>fractional second</strong>.</td>
<td style="padding: 5px;">
<p>123 ms → &#8220;12&#8221;</p>
<p>7 ms → &#8220;00&#8221;</td>
</tr>
<tr>
<td style="padding: 5px;">&#8220;SSS&#8221;</td>
<td style="padding: 5px;">
<p>Tenths, hundredths, and thousandths</p>
<p>place of a <strong>fractional second</strong>.</td>
<td style="padding: 5px;">
<p>123 ms → &#8220;123&#8221;</p>
<p>7 ms → &#8220;007&#8221;</td>
</tr>
</tbody>
</table>
<p>Two things to note about the fractional second.  First, it does not round, it just shows the appropriate places (otherwise the 2 digit fractional second would show 7 ms as &#8220;01&#8221;).  Secondly, the Unicode standard lets you use as many as you want, so &#8220;SSSSS&#8221; is valid.  However, DateFormatter will not show anything below milliseconds, it will just show 0s below that.  So 123456789 nanoseconds with a &#8220;SSSSSSSSS&#8221; format string will show up as &#8220;123000000&#8221;.</p>
<p>One major thing to note, there is a difference between &#8220;yyyy&#8221; and &#8220;YYYY&#8221;.  In most cases, you probably want to use the lowercase one, &#8220;yyyy&#8221;.  The uppercase one is the &#8220;Week of Year&#8221; style of year.  If you&#8217;re curious about the &#8220;Week of Year&#8221; style of year, it is based off of something called the ISO Week Date, which is part of the ISO 8601 standard.</p>
<p>Suffice it to say though, you want to usually use &#8220;<strong>yyyy</strong>&#8221; in your DateFormatter, unless you are writing a Swift app for an institution that needs to use the ISO Week Date.</p>
<p>Now, there is one issue with using the fixed format style of custom formats.  The reason they are called &#8220;fixed formats&#8221;, is because they print out exactly what you say, in the same order.  That&#8217;s all well and good in your locale and calendar system, but (especially with the short date style) 06/02/2014 and 02/06/2014 are very different dates.  One is the day Swift was released, the other is Rick Astley&#8217;s 48th birthday.  If I gave a custom format string of &#8220;MM/dd/yyyy&#8221; to show Swift&#8217;s birthday to app users in Great Britain, they&#8217;ll be wondering if I Rickrolled them.</p>
<p>Luckily, Apple built-in a great method to DateFormatter to help us avoid this accidental Rickrolling.</p>
<h2>The dateFormatFromTemplate method</h2>
<p>You tell this DateFormatter class method what components you want, using the same format strings as used in the fixed format, and a locale, and it will give you a date format string that is appropriate for your locale.  A very similar example of this was done in Apple&#8217;s Documentation:  <a title="Data Formatting Guide: Date Formatters" href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW14">Data Formatting Guide: Date Formatters</a>.  So, let&#8217;s tell it to generate the appropriate format strings for the en-US locale, and the en-GB locale:</p>
<pre class="lang:swift decode:true">let usDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
//usDateFormat now contains an optional string "MM/dd/yyyy".

let gbDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
//gbDateFormat now contains an optional string "dd/MM/yyyy"</pre>
<p>There are a few things to notice about this method.  Firstly, to repeat, this is a class method, so it is being called on the DateFormatter class itself, not a specific instance of it.</p>
<p>Secondly, the template used is the same.  It can be in any order, I just chose my default of the US order.  It just needs to know what components you want, it will figure out what to do with them based on the locale specified.</p>
<p>Thirdly, ignore the options method.  It appears to be there in case options are needed later, but according to the docs, there are no options defined yet, and you should just give it 0.</p>
<p>Fourthly, you probably would use Locale.current for the locale parameter.  Unless you are trying to show how different locales and calendars would show the date provided, the &#8220;current&#8221; constant will show what makes sense for that user&#8217;s iOS device.  I just hard coded it here to show it explicitly in the code what it was set to.</p>
<p>Finally, this actually returns an optional string, probably in case it cannot make a suitable dateFormat String from the template provided.</p>
<p>So now, we can use this like we used the fixed custom format string, by setting an instance of DateFormatter&#8217;s dateFormat property to it:</p>
<pre class="lang:swift decode:true">formatter.dateFormat = usDateFormat
let usSwiftDayString = formatter.string(from: swiftDay)
// usSwiftDayString now contains the string "06/02/2014".


formatter.dateFormat = gbDateFormat
let gbSwiftDayString = formatter.string(from: swiftDay)
// gbSwiftDayString now contains the string "02/06/2014".</pre>
<p>There, now I won&#8217;t accidentally Rickroll my friends at <a title="Swift London (@SwiftLDN) | Twitter" href="https://twitter.com/SwiftLDN">@SwiftLDN</a>, or other readers in Great Britain.</p>
<h2>Conclusion</h2>
<p>After realizing the inverted date of Swift&#8217;s announcement was Rick Astley&#8217;s birthday, I had trouble not using a Rick Astley song title pun as the title to this post.</p>
<p>Much like how DateComponents made it a lot easier to work with Dates in your Swift code, with setting the individual components directly, DateFormatter gives you a lot of power in how you want an Date to appear to your Swift app&#8217;s users.  There is even more power than what I showed here, but I felt that the chart would be big enough without including less used components like the quarter or theISO Week Date style of years.  Nonetheless though, you can check those out at the Unicode Standard to get the rest of the values if you need them for your instance of DateFormatter.</p>
<p>This of course was the Swift version of how to use DateFormatter.  If you want to see how to use it in Objective-C, check out the previous post <a title="Displaying a human readable Date" href="http://www.codingexplorer.com/displaying-a-human-readable-nsdate/">Displaying a human readable NSDate</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="DateFormatter Class Reference" href="https://developer.apple.com/documentation/foundation/dateformatter">DateFormatter Class Reference &#8211; Apple Inc.</a></li>
<li><a title="Data Formatting Guide: Date Formatters" href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html">Data Formatting Guide: Date Formatters &#8211; Apple Inc.</a></li>
<li><a title="UTS #35: Unicode LDML: Dates" href="http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns">UTS #35-31: Unicode LDML: Dates &#8211; Unicode, Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/">Swiftly getting a human-readable date with NSDateFormatter</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>NSUserDefaults — A Swift Introduction</title>
		<link>https://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 17 Dec 2014 14:30:49 +0000</pubDate>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[optionals]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=783</guid>

					<description><![CDATA[<p>So, let&#8217;s say we have an app that needs to remember a few simple things that the user puts in when they first load the app.  It needs to remember the user&#8217;s name and birthday, to show on some view controller, or maybe even for a countdown on their Apple Watch. There are plenty of [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/">NSUserDefaults — A Swift Introduction</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So, let&#8217;s say we have an app that needs to remember a few simple things that the user puts in when they first load the app.  It needs to remember the user&#8217;s name and birthday, to show on some view controller, or maybe even for a countdown on their Apple Watch.</p>
<p>There are plenty of ways to save data for your app.  Some are easy to use, but rather limited, while others are much harder to use, but give you a lot more capabilities.  Today, we are going to cover something on the easy, but limited end of the spectrum.  For the app mentioned above, the information we&#8217;re storing will be used to set this app up with default values, for this user anyway.</p>
<p>That is why this method is called NSUserDefaults.  It has its limitations, but it is very easy to use, and is ideal for simple storage of things like Strings and numbers.<br />
<span id="more-783"></span></p>
<h2>Storable Types in NSUserDefaults</h2>
<p>The NSUserDefaults class acts very much like something called a Property List (aka plist).  It may be just a fancy interface for a plist, or it may be more, I&#8217;m not entirely sure.  Nonetheless, plists are limited in what kind of objects they can store.  The six types plists can store are:</p>
<ul>
<li>NSData</li>
<li>NSString</li>
<li>NSNumber</li>
<li>NSDate</li>
<li>NSArray</li>
<li>NSDictionary</li>
</ul>
<p>Just to make it clear, since they only differ by one letter, the first one listed as NSDat<span style="text-decoration: underline;"><strong>a</strong></span>, while the fourth one is an NSDat<span style="text-decoration: underline;"><strong>e</strong></span>.  A property list, or NSUserDefaults can store any type of object that can be converted to an NSData object.  It would require any custom class to implement that capability, but if it does, that can be stored as an NSData.  These are the only types that can be stored directly.  Thankfully, Swift Strings, Arrays, and Dictionaries are automatically converted to their NS counterparts, so they can be stored in here as well.</p>
<p>An NSNumber is an NSObject that can contain the original C style numeric types, which even include the C/Objective-C style BOOL type (that stores YES or NO).  Thankfully for us, these are also bridged to Swift, so for a Swift program, an NSNumber can automatically accept the following Swift types:</p>
<ul>
<li>UInt</li>
<li>Int</li>
<li>Float</li>
<li>Double</li>
<li>Bool</li>
</ul>
<p>That final one is that Swift style Bool that stores the value of &#8220;true&#8221; or &#8220;false&#8221;.  Nonetheless, if we want to expand this out slightly to show The Swift versions instead of their Objective-C forms, where applicable, you can store the types:</p>
<ul>
<li>Data</li>
<li>String</li>
<li>NSNumber
<ul>
<li>UInt</li>
<li>Int</li>
<li>Float</li>
<li>Double</li>
<li>Bool</li>
</ul>
</li>
<li>Date</li>
<li>Array</li>
<li>Dictionary</li>
</ul>
<h2>Writing to NSUserDefaults</h2>
<p>First, to read from or write to NSUserDefaults, you have to get a reference to it.  In the simplest use of NSUserDefaults, this is done via a method that returns a reference to an object capable of interacting with NSUserDefaults&#8217;s data store.  This method returns something very much like a singleton.  A singleton is an object that only has one instance of it generated per program.  When you call the class method the first time, the object is instantiated and a reference is passed back.  When you call that method again, it does not instantiate a new one, and passes the aforementioned reference again, making both point to the same instance.  Singletons are often viewed as an anti-pattern, particularly since they are difficult to test with.  They are often used to give global state to apps, which hide dependencies within the single reference to a large object, instead of having them explicitly injected through a type&#8217;s public interface or protocol.</p>
<p>Nonetheless, we are not covering singletons in general today, but just be aware that while this is effectively a singleton, you should be careful about using the design pattern yourself.  When I use NSUserDefaults, I have had all of its accesses tucked away in a single class, that if I want to test, I can just replace that single class with another one that adopts the same protocol that has the values I want to test with (and thus side-step using NSUserDefaults altogether in the test, I&#8217;m not supposed to be testing NSUserDefaults itself).</p>
<p>Anyway, all that to say that we basically need to get a reference to NSUserDefaults, and then ask it to save something.  Below is sample code of how to do that:</p>
<pre class="lang:default decode:true">let defaults = UserDefaults.standard
defaults.set("Coding Explorer", forKey: "userNameKey")</pre>
<p>So, the first line is getting a reference to something that can access NSUserDefaults with the standard class property.  After that, we tell it to set an object with a specific key.  In this case, we are storing the user name, which I put in as &#8220;Coding Explorer&#8221;, and then give that a key to use to recall it later, similar to using a Dictionary.</p>
<p>There are several convenience methods for storing data in NSUserDefaults they include:</p>
<ul>
<li><span style="color: #b833a1;">func</span> set(_ value: <span style="color: #703daa;">Bool</span>, forKey defaultName: <span style="color: #703daa;">String</span>)</li>
<li><span style="color: #b833a1;">func</span> set(_ value: <span style="color: #703daa;">Int</span>, forKey defaultName: <span style="color: #703daa;">String</span>)</li>
<li><span style="color: #b833a1;">func</span> set(_ value: <span style="color: #703daa;">Float</span>, forKey defaultName: <span style="color: #703daa;">String</span>)</li>
<li><span style="color: #b833a1;">func</span> set(_ value: <span style="color: #703daa;">Double</span>, forKey defaultName: <span style="color: #703daa;">String</span>)</li>
<li><span style="color: #b833a1;">func</span> set(_ value: <span style="color: #703daa;">Any</span>?, forKey defaultName: <span style="color: #703daa;">String</span>)</li>
<li><span style="color: #b833a1;">func</span> set(_ url: <span style="color: #703daa;">URL</span>?, forKey defaultName: <span style="color: #703daa;">String</span>)</li>
</ul>
<h2>Reading from NSUserDefaults</h2>
<p>Reading is done in a very similar fashion.  You need to get a reference to the NSUserDefaults object, and then ask it for the value you want.  In the case of reading out the String we wrote in and printing it to the console, we would use the code:</p>
<pre class="lang:swift decode:true">let defaults = UserDefaults.standard
if let name = defaults.string(forKey: "userNameKey") {
    print(name)
}</pre>
<p>The methods to read something out, similar to a dictionary, return an Optional of whatever you are looking for, if it can. That way, if something does NOT exist for the key you used, it would return nil.  So, in this example, we optionally bind the output of stringForKey(&#8220;userNameKey&#8221;) to the constant &#8220;name&#8221;.  If it exists at that key, then we store it in the name constant, and go into the if statement and proceed with the code in there (to print the &#8220;name&#8221; String).  Otherwise, if a value is not found for that key, that if statement results in a false and thus we don&#8217;t try to access the value since it is actually nil.</p>
<p>Much like writing to NSUserDefaults, there are several convenience methods for reading data back out, that are a bit more full featured than writing them:</p>
<ul>
<li><span style="color: #b833a1;">func</span> boolForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; <span style="color: #703daa;">Bool</span></li>
<li><span style="color: #b833a1;">func</span> integerForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; <span style="color: #703daa;">Int</span></li>
<li><span style="color: #b833a1;">func</span> floatForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; <span style="color: #703daa;">Float</span></li>
<li><span style="color: #b833a1;">func</span> doubleForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; <span style="color: #703daa;">Double</span></li>
<li><span style="color: #b833a1;">func</span> objectForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; <span style="color: #703daa;">AnyObject</span>?</li>
<li><span style="color: #b833a1;">func</span> URLForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; <span style="color: #703daa;">NSURL</span>?</li>
<li><span style="color: #b833a1;">func</span> dataForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; <span style="color: #703daa;">NSData</span>?</li>
<li><span style="color: #b833a1;">func</span> stringForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; <span style="color: #703daa;">String</span>?</li>
<li><span style="color: #b833a1;">func</span> stringArrayForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; [<span style="color: #703daa;">String</span>]?</li>
<li><span style="color: #b833a1;">func</span> arrayForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; [<span style="color: #703daa;">AnyObject</span>]?</li>
<li><span style="color: #b833a1;">func</span> dictionaryForKey(defaultName: <span style="color: #703daa;">String</span>) -&gt; [<span style="color: #703daa;">String</span> : <span style="color: #703daa;">AnyObject</span>]?</li>
</ul>
<p>Since this is an Objective-C class there are some caveats to how this works, that makes it a bit odd for Swift.  First, you will notice that the ones that read Bool, Int, Float, and Double do not return Optionals.  In Objective-C, this returns the C primitive types for those variables.  As such, they could not be set to nil, since they weren&#8217;t Objective-C objects.  In those cases, they return sentinel values appropriate to their types which are false (or NO), 0, 0.0, and 0.0 respectively.  Maybe someday this class will be modified to have them return Optionals in Swift eventually, but for now, this is how they work.</p>
<p>Next, in Objective-C, NSArrays and NSDictionaries could store any type of object in them.  You could have an NSArray holding types like  NSInteger, NSViewController, UIImage, or UIActivityViewController all in the same NSArray.  As such, the types coming out of NSArrays or NSDictionaries were of the Objective-C type &#8220;id&#8221;, which translates to &#8220;ANYObject&#8221; in Swift.  That&#8217;s why stringArrayForKey, arrayForKey, and dictionaryForKey return with AnyObject in their return types.  In the case of objectForKey, that is exactly what you&#8217;re asking for, so that one makes sense.</p>
<p>In the case of storing an NSDate, you will have to store it as an NSObject, and type-cast it back to an NSDate when you read it back out.  For any other type of value not included in the major plist storage types, you will have to encode it into an NSData, write that with setObject:ForKey:, and read it back with dataForKey:.  I have not learned much about NSCoding yet, but that is what you would use for archiving custom classes to NSData.</p>
<h2>Use Constants for your Keys</h2>
<p>Now, for simplicity, I wrote the Swift String literal each time I wrote the key.  I didn&#8217;t want to set up what I&#8217;m about to say beforehand just to make the code to access a value from NSUserDefaults as easy to understand as possible (to know for sure there is a String there).</p>
<p>Doing it THAT way in production code is a very bad idea.</p>
<p>Instead, you should create a constant for that value, and assign the Swift String Literal to it.  This helps for a few reasons:</p>
<ol>
<li>If you need to change the literal for some reason, you only have to change it in one place.</li>
<li>Xcode can now help autocomplete the constant&#8217;s name in your method call.</li>
<li>If you make a typo with the constant name, you get a compile-time error (while a typo in a String literal is a run-time error).</li>
</ol>
<p>So, here is some example code that has 2 buttons running the previous code, but with a constant defined:</p>
<pre class="lang:default decode:true">let userNameKeyConstant = "userNameKey"

@IBAction func writeButtonWasTapped(_ sender: UIButton) {
    let defaults = UserDefaults.standard
    defaults.set("Coding Explorer", forKey: "userNameKey")
}

@IBAction func readButtonWasTapped(_ sender: UIButton) {
    let defaults = UserDefaults.standard

    if let name = defaults.string(forKey: userNameKeyConstant) {
        print(name)
    }
}</pre>
<p>I actually tend to have the value stored in the key constant be the same as the variable name, but I wanted to show here clearly that you don&#8217;t have to (the constant is named &#8220;userNameKeyConstant&#8221; while the actual String stored within is &#8220;userNameKey&#8221;).  As you can see, the code is pretty much the same, just with that new constant instead of the String literal.  I defined the constant at the class scope (which means within the class&#8217;s curly braces, the class declaration was not shown in this example), and used it in the individual methods.</p>
<h2>Conclusion</h2>
<p>NSUserDefaults is ideal for storing small bits of information between app launches.  Its API is very simple, and does its job well.  It does show its Objective-C roots in Swift moreso than some other classes, but it still gets the job done.</p>
<p>It is best when used for little information like user preferences, but not for larger things like UIImages.  If want to store more complex things, it is better to use some of the more full-featured forms of data persistence.  You could work directly with a plist yourself, write the file to disk, or even use Core Data.  We can cover these later, but I figured starting with the simplest form would be best.</p>
<p>NSUserDefaults is in general read from, and written to, atomically.  This is good for making sure the data is read and written correctly, but as such it is ALL written when something changes.  So if you have something in there, and you change something small like a bool, the whole thing needs to be written again, so even though only a small part has changed, you&#8217;re still writing back out that large part.  Same thing for reading.  If you only needed to read that boolean, when NSUserDefaults first loads, it will still read everything, and then just give you the bool you requested.  It is cached after the initial load, so it shouldn&#8217;t be too slow afterwards, but the initial read could be quite slow with larger amounts of data.</p>
<p>There is another reason for looking into NSUserDefaults.  Using NSUserDefaults in combination with App Groups is the simplest way to share data between your app and any extensions it has.  We have not covered that in this post, it is already over 2,000 words long at this point, so we&#8217;ll cover that in a more specialized post.  Extensions should load quickly, so you still don&#8217;t want to put much in there, but preferences like Strings are easily shared between apps and their extensions using this method.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-NSUserDefaultsIntroSwift">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a href="https://itunes.apple.com/us/book/using-swift-cocoa-objective/id888894773?mt=11&amp;uo=4&amp;at=10lJ3x;ct=blog-NSUserDefaultsIntroSwift" target="itunes_store" rel="noopener noreferrer">Using Swift with Cocoa and Objective-C &#8211; Apple Inc.</a></li>
<li><a title="NSUserDefaults Class Reference" href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html">NSUserDefaults Class Reference — Apple Inc.</a></li>
<li><a title="NSNumber Class Reference" href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/index.html">NSNumber Class Reference — Apple Inc.</a></li>
<li><a title="Mac OS X Developer Release Note" href="https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_10UserDefaults">Mac OS X Developer Release Note — NSUserDefaults — Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/">NSUserDefaults — A Swift Introduction</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Custom Operators in Swift</title>
		<link>https://www.codingexplorer.com/custom-operators-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 09 Dec 2014 20:55:57 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=754</guid>

					<description><![CDATA[<p>You have been spared the terrible pun for this title, I knew the last one was trouble when it was typed in. So, in the earlier article Operator Overloading — Tailor Swift To Your Needs, you saw how you could add functionality to already existing operators to extend their functionality to work with new classes, or [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/custom-operators-swift/">Custom Operators in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>You have been spared the terrible pun for this title, I knew the last one was trouble when it was typed in.</p>
<p>So, in the earlier article <a title="Operator Overloading — Tailor Swift To Your Needs" href="http://www.codingexplorer.com/swift-operator-overloading/">Operator Overloading — Tailor Swift To Your Needs</a>, you saw how you could add functionality to already existing operators to extend their functionality to work with new classes, or in that post&#8217;s case, existing ones that it might make sense with.  Now, what if you want a completely new operator?  What if you have functionality so unique, that no current operator makes sense?  That&#8217;s where custom operators comes in.  You can declare your own operator and have it run whatever code you want.  Now, like last time, this is a very powerful, but very dangerous capability.  You COULD have it play sounds, make network calls, draw something to screen, or any number of annoying things, but you really should not have those in your operator overloading or custom operator methods.  They are meant to make things more readable, not less.  Unless you use some emoji for a loudspeaker in your operators, you really shouldn&#8217;t have it play sounds, and even if you do, why not just use a method?</p>
<p>Also of course, since these are meant to increase readability, you have to be careful about using these.  For instance, can you tell me what the &#8221; #$^&amp;* &#8221; operator does?  Obviously somebody new to a codebase needs some time to get up to speed with it, and even normal functions will take some time to learn the intricacies of.  However, if you compress a gigantic algorithm into a custom operator, that may take longer to figure out than a well named method doing the same.</p>
<p>Nonetheless though, if you use custom operators sparingly, well document them, and don&#8217;t give them side effects (like making network calls, playing sounds, etc), they can very useful for increasing legibility and decreasing the character count in your code.<br />
<span id="more-754"></span></p>
<h2>Types of Custom Operators</h2>
<p>In Swift, there can be operators that operate on 1, 2, or 3 values.  We call those operators unary, binary, or ternary (respectively).</p>
<p>Swift has 4 types of operators, 3 of which are available for us to use with custom operators they are:</p>
<table border="1">
<tbody>
<tr>
<td style="padding: 5px;"><strong>Keyword</strong></td>
<td style="padding: 5px;"><strong>Description</strong></td>
</tr>
<tr>
<td style="padding: 5px;">prefix</td>
<td style="padding: 5px;">A unary (operating on one value) operator that is just <strong>before</strong> the value it operates on.</td>
</tr>
<tr>
<td style="padding: 5px;">postfix</td>
<td style="padding: 5px;">A unary operator that is just <strong>after</strong> the value it operates on.</td>
</tr>
<tr>
<td style="padding: 5px;">infix</td>
<td style="padding: 5px;">A binary (operating on two values) operator placed <strong>between</strong> the two values it operates on.</td>
</tr>
</tbody>
</table>
<p>There is a fourth style of operator in Swift known as the ternary operator.  It is not included in the above table though, because currently we cannot write our own ternary operator functions.  The Swift language itself has only one ternary function, a conditional operator.  It was mentioned as how the nil-coalescing operator works under the hood in the previous article <a title="Nil Coalescing in Swift" href="http://www.codingexplorer.com/nil-coalescing-swift/">Nil Coalescing in Swift</a>.</p>
<p>You use these keywords when declaring your operator, letting Swift know that your combination of symbols is an operator, and how it will be used with the value(s) it uses or modifies.</p>
<h2>Implementing A Postfix or Prefix Operator</h2>
<p>I was never the biggest fan of using the &#8221; % &#8221; key on a calculator, I always preferred just typing the percentage as a decimal.  But, presumably people did use it, so that seemed like a great example of a postfix operator.  The basic idea will be for it to be a postfix operator that will take in an Integer and return a Double that is the decimal version of that percentage, such that 42% == 0.42.</p>
<p>It could take a Double as an input too, but it will be the same code, just with a function overload to take the Double instead of the Integer.  Also, unlike other postfix operators (like ++ or &#8211;), this one will not modify the value that is passed in.</p>
<p>Since the code to perform this is so small, I will just show it all below and explain it afterwards:</p>
<pre class="lang:swift decode:true">postfix operator % {}

postfix func % (percentage: Int) -&gt; Double {
    return (Double(percentage) / 100)
}</pre>
<p>Now, the astute among you may remember that there actually is a &#8221; % &#8221; operator in Swift.  In Swift, the &#8221; % &#8221; operator is a remainder operator.  It is used like the division operator, but instead of returning the quotient of the division operation, it returns the remainder.  However though, that operator, since it operates on two values is an infix operator.  There are no &#8221; % &#8221; postfix operators built into Swift, so we had to declare it as a new one.</p>
<p>So, for the first line, we declared that it is an operator, that it is a postfix one (so placed immediately after value it uses), and that its symbol is &#8221; % &#8220;.  For unary operator (prefix or postfix), those brackets must be there, but they should be empty.  We will see what they are used for when we discuss infix operators.</p>
<p>Then, similar to operator overloading, we create a function for our new operator.  We specify that it is still a postfix operator, and then follow it up with the rest of the normal way of writing a function.  As said earlier, this operator will operate on an Integer, and return a Double.  We then just write a normal function.  First the &#8220;percentage&#8221; Integer is cast to a Double, and then that new Double is divided by 100.  The result of this calculation is returned by the function.</p>
<p>If you wanted to also take a Double as the input, all you would have to do is change the &#8220;percentage&#8221; parameter type to Double, and remove that cast to Double in the function.</p>
<p>So with the above code, the code below will now be valid in the same module:</p>
<pre class="lang:swift decode:true">let fivePercent = 5%
// fivePercent is now a Double that holds the value 0.05

let fortyTwoPercent = 42%
// fivePercent is now a Double that holds the value 0.42</pre>
<p>To implement a prefix operator, you really just do the same thing as for the postfix, but just with the &#8220;prefix&#8221; operator instead of &#8220;postfix&#8221;.  It doesn&#8217;t look as pretty, but just for the sake of having an example, here is the % changed into a prefix operator (same code otherwise):</p>
<pre class="lang:swift decode:true">prefix operator %

prefix func % (percentage: Int) -&gt; Double {
    return (Double(percentage) / 100)
}

//Example Use

let fortyTwoPercent = %42
// fivePercent is now a Double that holds the value 0.42</pre>
<p>I definitely prefer it as a postfix operator, but this just shows you how similar writing a prefix and postfix operator are.</p>
<h2>Implementing an Infix Operator</h2>
<p>These operators are the kind that operate on two values, placed between them.  The most notable examples are that standard arithmetic operators like +, -, *, and /.  So when you add, you use it like in the expression &#8221; a + b &#8220;, placing it between them.</p>
<p>Currently in Swift there is a &#8221; ^ &#8221; infix operator.  It is used for the bitwise exclusive OR function.  When used in a mathematic context though, it is often used to refer to raising something to a power, like 5^2 would mean &#8220;Five squared&#8221; or &#8220;Five raised to the power of two&#8221;.  I don&#8217;t want to use the &#8221; ^ &#8221; operator since that is already used for the XOR function, so let&#8217;s use an operator based on it, but different enough to not be confused, like &#8221; ^^^ &#8220;.  With 3 ^s in a row, it is much less likely to mistake it than if we had only 2.</p>
<p>Below is the code for implementing the &#8221; ^^^ &#8221; operator for raising a number to a power:</p>
<pre class="lang:swift decode:true">precedencegroup ExponentialPrecedence {
    lowerThan: BitwiseShiftPrecedence
    higherThan: MultiplicationPrecedence
    associativity: right
}

infix operator ^^^: ExponentialPrecedence

func ^^^ (base: Int, power: Int) -&gt; Double
{
    return pow(Double(base), Double(power))
}</pre>
<p>For infix operators, you have to specify the associativity and the precedence for an operator.  So what are those values in the precedencegroup?  It might be easier to show this one by example.</p>
<p>The division operator is left associative, as such, the expression  7.5 / 4.0 / 2.5 = 0.75.</p>
<p>If we used parenthesis to show what it is actually doing, the <strong>correct</strong> expression would be:</p>
<ul>
<li>(7.5 / 4.0) / 2.5.</li>
<li>(1.875) / 2.5</li>
<li>0.75</li>
</ul>
<p>If we decided to make it right-associative (which is <strong>wrong</strong> for division, but showing how it changes things) we would get the expression:</p>
<ul>
<li>7.5 / (4.0 / 2.5)</li>
<li>7.5 / (1.6)</li>
<li>4.6875</li>
</ul>
<p>Very different.  The exponentiation operator is right associative, so 5^4^2 is equivalent to 5^(4^2).  This is why we should use right associativity.  You have the choice of <strong>right</strong>, <strong>none</strong>, or <strong>left</strong>.  You can read more about operator associativity in this <a title="Operator associativity - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Operator_associativity">Wikipedia article</a>.</p>
<p>The next value is precedence.  This determines for values with the same associativity, which ones should be evaluated first.  In this case, I defaulted to good ol&#8217; PEMDAS.  On the <a href="https://developer.apple.com/documentation/swift/swift_standard_library/operator_declarations">Operator Declarations</a> page of Apple&#8217;s developer site, you can see the associativity and precedence for operators in Swift. Parenthesis and exponents have higher precedence than Multiplication, so in the ExponentialPrecedence group we defined, we set the precedence higher than the MultiplicationPrecedence that is built into Swift.  Bitwise Shift operations have the highest precedence, and since this is working with numbers instead of bits, it seems logical to have an exponential operator be lower than the BitwiseShiftPrecedence.  This might be wrong, but this is just an example of how to make custom operators, not math class.</p>
<p>Nonetheless, once those are set, we assign that precedencegroup to our new ^^^ operator, and after that, we actually write the <strong>function</strong> itself.  One thing to note is that you don&#8217;t have to write &#8220;infix&#8221; before your operator function, unlike how we had to write which kind for a prefix or postfix operator.  You do still have to write it when you declare the operator itself, just not the function that makes the operator DO something.  If you try to use it, you get an error.</p>
<p>If you do not specify the precedence and associativity, the default precedence is 100 and the default associativity is none.  This puts them right above assignment in precedence (as in saying assigning a value to a variable).</p>
<p>So now, with this operator, these expressions are now valid in your Swift module:</p>
<pre class="lang:swift decode:true">let fiveSquared = 5 ^^^ 2
// fiveSquared is now a Double that holds the value 25.0

let powerOfZero = 123456 ^^^ 0
// powerOfZero is now a Double that holds the value 1.0

let negativeExponent = 10 ^^^ -2
// negativeExponent is now a Double that holds the value 0.01</pre>
<h2>Conclusion</h2>
<p>As with its sibling, Operator Overloading, a certain cliché comes to mind.  I will spare you from hearing it another time, but there is tremendous responsibility in using this capability for good.  Custom operators can make code nigh unreadable if you are not careful, so do your best to make sure you choose a good set of symbols for your operator, and to document it very well.  It is also probably best not to make too many custom operators in the same project.  I&#8217;m not sure when I&#8217;ll use custom operators myself, but I am glad for the capability to do it when I DO find a need.</p>
<p>One more thing to note, all operator declarations and functions must be placed at global scope, outside of any type (class, structure, or enumeration).</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftCustomOperators">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Operator associativity - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Operator_associativity">Operator associativity — Wikipedia</a></li>
<li><a title="Facets of Swift, Part 5: Custom Operators — Swift Programming — Medium" href="https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc">Facets of Swift, Part 5: Custom Operators — Swift Programming — Medium</a></li>
<li><a title="Swift Operators - NSHipster" href="http://nshipster.com/swift-operators/">Swift Operators — NSHipster</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/custom-operators-swift/">Custom Operators in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>DateComponents — Class Reference</title>
		<link>https://www.codingexplorer.com/nsdatecomponents-class-reference/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 14 Nov 2014 15:30:14 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=722</guid>

					<description><![CDATA[<p>As mentioned last time in my post Date — Class Reference, now we go a bit more in depth with DateComponents.  In my opinion, this is the real powerhouse for dealing with time in Swift or Objective-C.  When I was first learning iOS, I looked, understandably, at Date to work with dates.  As such, a [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/nsdatecomponents-class-reference/">DateComponents — Class Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As mentioned last time in my post <a title="NSDate — Class Reference" href="http://www.codingexplorer.com/nsdate-class-reference/">Date — Class Reference</a>, now we go a bit more in depth with DateComponents.  In my opinion, this is the real powerhouse for dealing with time in Swift or Objective-C.  When I was first learning iOS, I looked, understandably, at Date to work with dates.  As such, a test project used Date and it&#8217;s initializers, including NSTimeInterval.  When I had mentioned that at my local NSCoderNight, I was told to look into DateComponents, and boy was that good advice!  Not only is it a pain to calculate the seconds for the intervals you want, what about dealing with Daylight Savings Time, leap years, or just plain different calendars!  Now with DateComponents, I can set a date in a way that I understand, and in concert with Date and Calendar, it will even deal appropriately with the intricacies of calendars without me having to do so myself.</p>
<p>DateComponents can be used to either specify a specific date, or to specify a timespan in your Swift iOS apps.  There is no difference between the uses as far as DateComponents is concerned you just set the appropriate components (year, day, hour, second, etc).<br />
<span id="more-722"></span></p>
<h2>The Components on DateComponents</h2>
<p>So, what can you specify with DateComponents?  Here is a list of all properties for a DateComponents object you can set, and any special notes about them as interpreted for the Gregorian Calendar.</p>
<table>
<tbody>
<tr>
<td>Property</td>
<td>Notes</td>
</tr>
<tr>
<td>era</td>
<td>Index for DateComponents&#8217;s EraSymbol Array, which is [&#8220;BC&#8221;, &#8220;AD&#8221;] for the Gregorian Calendar.</td>
</tr>
<tr>
<td>year</td>
<td></td>
</tr>
<tr>
<td>month</td>
<td></td>
</tr>
<tr>
<td>day</td>
<td></td>
</tr>
<tr>
<td>hour</td>
<td></td>
</tr>
<tr>
<td>minute</td>
<td></td>
</tr>
<tr>
<td>second</td>
<td></td>
</tr>
<tr>
<td>nanosecond</td>
<td></td>
</tr>
<tr>
<td>weekday</td>
<td>The index of which day of the week it is, so Sunday is 1, and Saturday is 7.</td>
</tr>
<tr>
<td>weekdayOrdinal</td>
<td>Works with the above weekday in specifying which weekday in the larger context (the month in this case).</td>
</tr>
<tr>
<td>quarter</td>
<td>The quarter of the year the date is in.</td>
</tr>
<tr>
<td>weekOfMonth</td>
<td>The week number within the month.</td>
</tr>
<tr>
<td>weekOfYear</td>
<td>The week number within the year based on the ISO week date.</td>
</tr>
<tr>
<td>yearForWeekOfYear</td>
<td>The year for the above weekOfYear based on the ISO week date.</td>
</tr>
<tr>
<td>isLeapMonth</td>
<td>Boolean of whether the month is a leap month (not used in Gregorian Calendar).</td>
</tr>
<tr>
<td>calendar</td>
<td>The Calendar this should be interpreted against.</td>
</tr>
<tr>
<td>timeZone</td>
<td>The NSTimeZone to interpret this DateComponents object.</td>
</tr>
</tbody>
</table>
<p>That is a lot of properties.  Also, if you&#8217;re curious the weekOfYear and yearForWeekOfYear are based off of something called the ISO Week Date, which is part of the ISO 8601 standard.  You can read more about it on <a title="&lt;title&gt;ISO week date - Wikipedia, the free encyclopedia&lt;/title&gt;" href="http://en.wikipedia.org/wiki/ISO_week_date"> this Wikipedia page</a>.  The 52nd week of the year as we normally use it may not be the 52nd week according to the weekOfYear property, depending on which year you are in, and what day of the week the year starts on in the normal Gregorian calendar (as opposed to the ISO Week Date version of the Gregorian Calendar).</p>
<p>A little more explanation on the weekday and weekdayOrdinal property.  They work together, so, for instance the day this post goes out is November 14, 2014.  The values for that are weekday of 6, and weekdayOrdinal of 2.  The weekday of 6 refers to a Friday.  The 2 says that this is the second of that weekday this month.  In other words, together they say that this is the second Friday of the month.</p>
<h2>Creating a DateComponents Object</h2>
<p>Unlike its predecessor NSDateComponents, Swift&#8217;s DateComponents has an initializer that lets you set the components directly, instead of having to create a blank one and fill them in later (like you used to).  The initializer has a whopping 16 parameters, but thankfully they all optional and have default values of nil, so you only need to define the ones you need, like so:</p>
<pre class="lang:swift decode:true">let swiftDayComponents = DateComponents(year: 2014, month: 6, day: 2)</pre>
<p>Those that are not set are internally set to nil.  By setting just the Year, Month, and Day of a date, you do not get the weekday or weekOfMonth values for free.  You actually have to fully construct a Date based on these components and create a new DateComponents object based off of that date to get that information calculated for you.</p>
<p>Now, if you want to make a Date out of that, the usual way is to create a Calendar instance and ask it to do so, like this:</p>
<pre class="lang:swift decode:true">if let swiftDate = Calendar.current.date(from: swiftDayComponents) {
    print(swiftDate)
}</pre>
<p>If you want, you could set the calendar property of your DateComponents object, and ask it to make a date for you as well:</p>
<pre class="lang:swift decode:true">let swiftDayComponents = DateComponents(calendar: .current, year: 2014, month: 6, day: 2)

if let swiftDate = swiftDayComponents.date {
    print(swiftDate)
}</pre>
<p>It just has to have some Calendrical context to be able to understand the DateComponents object.</p>
<h2>DateComponents&#8217;s Methods</h2>
<p>There are 4 methods in DateComponents.  They fall into two camps.  According to DateComponents&#8217; header file, they were all added in iOS 8.</p>
<h3>Accessing A Component</h3>
<p>The first two set  or get a component by specifying a Calendar.Component, instead of accessing them via dot-syntax.  This lets you dynamically request whichever one you wish, based on sending it the appropriate Calendar.Component.</p>
<pre class="lang:swift decode:true">mutableSwiftDayComponents.setValue(11, for: .hour)

let swiftHour = mutableSwiftDayComponents.value(for: .hour)
//swiftHour now equals 11.</pre>
<p>Those statements are equivalent to:</p>
<pre class="lang:swift decode:true">mutableSwiftDayComponents.hour = 11

let swiftHour = mutableSwiftDayComponents.hour</pre>
<p>It is more verbose, but if you need to be able to set a component, but you aren&#8217;t sure which one by compile-time, then these methods could be useful.</p>
<h3>Verifying Date Validity</h3>
<p>The other two verify if a DateComponents object is a valid date for a certain Calendar.  DateComponents can be used to denote a timespan, not only dates as we have shown so far.  They are not set up differently, but you can for instance set the seconds greater than 59, and it will just interpret that as however many minutes.  However, doing that would not be a valid date.  It would roll over, and show like a valid date, but why write 2 minutes, 129 seconds in a DateComponents object when you really mean 4 minutes, 9 seconds?  That is what these two methods check.</p>
<p>This one lets you get a bool denoting whether this date is valid in the current calendar:</p>
<pre class="lang:default decode:true">let dateValid = swiftDayComponents.isValidDate(in: .current)
//dateValid now equals true.</pre>
<p>The other one requires you to set the calendar property of the DateComponents object.  With that information you don&#8217;t need to specify to the method what calendar to check against like the previous method did.  You would use it like this:</p>
<pre class="lang:swift decode:true">mutableSwiftDayComponents.calendar = .current

let dateValid = mutableSwiftDayComponents.isValidDate
//dateValid now equals true.</pre>
<p>It actually is implemented, at least as far as Swift is concerned, more like a computed property, hence not having the parenthesis at the end of validDate.</p>
<p>The comments in DateComponents&#8217; header file do mention that these methods are &#8220;not necessarily cheap.&#8221;  Simple checks are fine, like our 129 seconds mentioned earlier, but checking more components makes this a bit more computationally intensive, so, be careful where you use these methods.</p>
<h2>Conclusion</h2>
<p>DateComponents makes it easy to specify a specific date and time, or even a timespan.  While it would make sense to put Date and DateComponents together as far as what they conceptually do, I believe they kept them separate for performance reasons.</p>
<p>DateComponents does a lot more than Date, and that adds a significant amount of overhead.  A Date is an immutable and lightweight object, making it very easy for the compiler to optimize.  When you ask a Calendar to create a Date from a DateComponents object, it takes the components and the intricacies of the calendar into account to make a Date object that stores just enough to specify a particular moment in time.</p>
<p>As a side note from the future, I am glad that now in swift you can use much cleaner Calendar.Components for setValue and valueFor methods.  In the original version of this its full name was NSCalendarUnit.HourCalendarUnit, but in the update to this post, you can just us Calendar.Component.hour (which, with Swift&#8217;s type inference was .HourCalendarUnit and now just .hour).  It is so much nicer to write .Hour instead of .HourCalendarUnit.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="NSDateComponents Class Reference" href="https://developer.apple.com/documentation/foundation/datecomponents">DateComponents Class Reference — Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/nsdatecomponents-class-reference/">DateComponents — Class Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Date — Class Reference</title>
		<link>https://www.codingexplorer.com/nsdate-class-reference/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 12 Nov 2014 21:41:00 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=715</guid>

					<description><![CDATA[<p>An NSDate object specifies a particular point in time.  Despite &#8220;date&#8221; being in its name, it really stores time, of which the date is a component.  Under the hood, NSDates (as far as the public superclass we can see is concerned) are specified as a number of seconds past a reference date.  NSDate&#8217;s reference date [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/nsdate-class-reference/">Date — Class Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>An NSDate object specifies a particular point in time.  Despite &#8220;date&#8221; being in its name, it really stores time, of which the date is a component.  Under the hood, NSDates (as far as the public superclass we can see is concerned) are specified as a number of seconds past a reference date.  NSDate&#8217;s reference date is the first moment of January 1, 2001 in the GMT timezone.  These seconds are stored as a Double, which allows NSDate to range from milliseconds to years.  What we see as an NSDate is actually an abstract public superclass for a cluster of classes related to dates.  The internal classes are private, so talking about them here wouldn&#8217;t be particularly helpful, and it is probably best not to mess with them anyway.</p>
<p>Since Swift 3 though, most &#8220;NS&#8221; prefixes were removed from the Swift Standard Library, so now it is simply called &#8220;Date&#8221;.  If you need to save a timestamp for something in your iOS app, or maybe have a countdown timer for an app or game, you will be dealing with the Date class, so let&#8217;s take a look at it.<br />
<span id="more-715"></span></p>
<h2>Creating an Date Object</h2>
<p>The Date class itself has 6 initializers:  3 dedicated and 3  convenience ones.  One dedicated initializer deals with Coding and 4 of them deal with TimeInterval.  I personally only use one of the built in initializers to Date, and that is the one that takes no arguments.  This one creates n Date object specifying the exact moment it was called.  It is incredibly simple:</p>
<pre class="lang:swift decode:true">//Prototype:  init()
let now = Date()</pre>
<p>That is all there is to it, now the &#8220;now&#8221; variable stores the exact moment this initializer was called.  I&#8217;ve used this in a few examples before to generate a simple class to test with.</p>
<p>I originally wrote this going through the other initializers that deal with TimeInterval, but decided to not include them.  TimeInterval is a typealias for a Double, and it specifies a certain number of seconds.  It has initializers for an TimeInterval since the reference date, since now, since the first moment of January 1, 1970 (the Unix epoch), and since any other Date object.</p>
<p>I don&#8217;t know about you, but I can&#8217;t really read a few million seconds and see that it is referring to this year.  Instead, if I need to specify a particular Date, I usually use DateComponents.  We will cover it a bit more in depth later, but for the moment, I will show a simple implementation of using this to create a certain Date:</p>
<pre class="lang:swift decode:true">let todayComponents = DateComponents(year: 2014, month: 11, day: 12)

if let todayDate = Calendar.current.date(from: todayComponents) {
    print(todayDate)
}

//Output: "2014-11-12 08:00:00 +0000"</pre>
<p>The first part is pretty simple.  You make a DateComponents object, and then set the components you wish.</p>
<p>An DateComponents object lets you set the components, but it has very little meaning without the context given by a Calendar.  Different calendrical systems have different numbers of seconds for some of these components, particularly for the length of a year.  So, to create a Date, we call that dateFromComponents method of the Calendar class and pass in the todayComponents object we just made.  The actual object we are calling that from is is the return of Calendar&#8217;s currentCalendar class function.  This returns an object specifying the current calendar that the device is set to.  You can specify one if you wish, but it is usually easier (and in many situations better) to use the current one for that device.</p>
<p>The dateFromComponents method returns an optional Date, so we can use optional binding to make it into a standard Date.  It could return nil if it is unable to convert the components to a specific time for some reason.  If you set a component out of its normal bounds, it will usually roll over.  For instance, if you set the minutes component to 1, and the seconds component to 121 seconds, this will return something with the  will be interpreted as 2 minutes and one second, and just add to the already specified minute value, so resulting in 3 minutes and 1 second.  I am not sure when it is unable to actually generate an Date from components, but I know very little about other Calendars, so maybe it has more to do with the conversions or idiosyncrasies between how other calendars handle the components compared to the Gregorian calendar.  Nonetheless, this can return nil, so I would suggest either checking it against nil before force unwrapping, or just using Swift&#8217;s Optional Binding syntax when using this for your iOS apps.</p>
<p>Also, apparently this calculation uses the time zone for your computer, so that is the reason it returned 8 AM in the GMT timezone.  This computer&#8217;s time zone is the Pacific Timezone, which is -8 GMT, as such midnight here (as specified by not setting the hour, minute, second, etc components, corresponds to 8 AM GMT.  If we had also set the timezone explicitly as GMT in our DateComponents object, it would return a value with 0 hours with 0 hours offset.</p>
<h2>Comparing Dates</h2>
<p>Date comes with 4 instance methods to compare dates.  The first we will talk about is the most general, the compare method.  This method returns an ComparisonResult, which is an enumeration that says whether a date is before, same as, or after another date.  I&#8217;ve personally found ComparisonResult difficult to remember which way means what, but Apple provided a nice explanation, which I will paraphrase in tabular form below:</p>
<table border="1">
<tbody>
<tr>
<td><strong>ComparisonResult</strong></td>
<td><strong> Meaning</strong></td>
</tr>
<tr>
<td>orderedAscending</td>
<td>Instance Date is <strong>earlier</strong> than anotherDate.</td>
</tr>
<tr>
<td>orderedSame</td>
<td>Instance Date and anotherDate are equal.</td>
</tr>
<tr>
<td>orderedDescending</td>
<td>Instance date is <strong>later</strong> than anotherDate.</td>
</tr>
</tbody>
</table>
<p>Here is some code to test it in a Swift Playground:</p>
<pre class="lang:swift decode:true">let result = now.compare(hourFromNow)

if result == .orderedAscending {
    print("Earlier")
} else if result == .orderedDescending {
    print("Later")
}

//Outputs:  "Earlier"</pre>
<h2>Conclusion</h2>
<p>The Date abstract class itself is a pretty simple interface.  It has some initializers, and basic comparisons between different Date classes, and that&#8217;s about it.</p>
<p>If you really want to get a lot of use out of it, you will need to work with a few different classes like DateComponents, Calendar, and DateFormatter.  I have covered DateFormatter a bit in Objective-C, but there will probably be a <a href="http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/">Swift version soon enough</a>.  We&#8217;ll cover DateComponents <a href="http://www.codingexplorer.com/nsdatecomponents-class-reference/">a bit more in depth later</a>, but I felt it was better to give some information about it now because it is a whole lot easier to create an Date object with DateFormatter than with an TimeInterval (at least if you have to work with more than a day&#8217;s worth of time anyway).</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="NSDate Class Reference" href="https://developer.apple.com/documentation/foundation/date">Date Class Reference — Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/nsdate-class-reference/">Date — Class Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Add sharing to your Swift app via UIActivityViewController</title>
		<link>https://www.codingexplorer.com/sharing-swift-app-uiactivityviewcontroller/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 10 Nov 2014 15:34:59 +0000</pubDate>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=703</guid>

					<description><![CDATA[<p>In several iOS apps, such as Safari or the Camera app, you can click a button that brings up an interface that makes it easy to send or share what you are looking at via messages, Twitter, Facebook, etc.  That interface is known as the UIActivityViewController.  When I first learned about it, I didn&#8217;t even [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/sharing-swift-app-uiactivityviewcontroller/">Add sharing to your Swift app via UIActivityViewController</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In several iOS apps, such as Safari or the Camera app, you can click a button that brings up an interface that makes it easy to send or share what you are looking at via messages, Twitter, Facebook, etc.  That interface is known as the UIActivityViewController.  When I first learned about it, I didn&#8217;t even know what to search for.  I think I originally started with &#8220;share sheet&#8221; and went on from there, so it may seem silly to point out something so obvious, but when I first tried, I knew what I wanted, I just had <strong>no idea</strong> what it was called.</p>
<p>If you&#8217;ve paid any attention to WWDC a few years, you have probably saw that this is the new home for Share and Action extensions.  Today though, we are just going to cover the built in aspects of using UIActivityViewController in your Swift app.  We will cover those sometime later.<br />
<span id="more-703"></span></p>
<h2>Presenting the UIActivityViewController</h2>
<p>UIActivityViewController is an Objective-C API.  Not a lot has changed about it between iOS 7 and iOS 9.  You will see a few things that are unusual in this code compared to standard Swift code, but thanks to Apple&#8217;s work on interoperability with Objective-C, it works just fine.</p>
<p>Here is (almost) the most basic code for loading a UIActivityViewController:</p>
<pre class="lang:swift decode:true">@IBAction func shareButtonTapped(_ sender: UIButton) {
    let textToShare = "Swift is awesome!  Check out this website about it!"

    if let myWebsite = NSURL(string: "http://www.codingexplorer.com/") {
        let objectsToShare: [Any] = [textToShare, myWebsite]
        let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

        activityVC.popoverPresentationController?.sourceView = sender
        self.present(activityVC, animated: true, completion: nil)
    }
}</pre>
<p>So, you can see that we put this into an IBAction connected to a button to trigger the sharing.  Next we make a String to share.  The next line is a bit more complex, but bear with me for a second.  That initializer for NSURL is a failable initializer.  We send it a string, and if it can create a valid URL, then it will return one.  However if it cannot, it will return a nil value.  We can use Optional Binding to change it back from an NSURL? (optional NSURL) to a normal NSURL.  I could have just forcefully unwrapped, since that is indeed a valid URL, but I personally do not like using the force unwrap operator if I don&#8217;t absolutely have to.  This is why I said it was &#8220;almost&#8221; the most basic code.</p>
<p>Anyway, now that we have our textToShare and myWebsite constants ready, we put them into an array.  Wait&#8230; what?  That&#8217;s an array of a String and an NSURL!  Swift arrays can only take values of the same type can&#8217;t they?  This is the first place where we see some of the Objective-C showing through.  The UIActivityViewController initializer we are about to call takes an NSArray as its first argument.  NSArrays can hold any type of object in the same array (unlike Swift Arrays).  When this is brought over to Swift, the function prototype for the initializer is:</p>
<pre class="lang:swift decode:true">init(activityItems: [Any], applicationActivities: [UIActivity]?)</pre>
<p>In Swift, an NSArray is shown as a Swift Array of the type AnyObject.  AnyObject represents an instance of any class type.  Since a Swift String and an NSURL are both classes, they technically can be in the same array, but they are cast as AnyObject instead of their primary type.</p>
<p>So, we create our UIActivityViewController with an initializer that takes that array of activityItems, and we set nil as the applicationActivities argument.  The applicationActivities parameter takes an array of UIActivity types that are custom to your application.  This was particularly useful before extensions.  This would allow you to say, make your own custom save to Instapaper button, and add it into the UIActivityViewController yourself.  With the new sharing extensions though, the creator of the app to share with can do the work for you.  Nonetheless, if you do have some special type of share or action activity that is inherent to your app (or to work with another service that does not have it&#8217;s own extension yet), this is where you would put it.  Since we have none, we just set it to nil.</p>
<p>I did say that applicationActivities takes an array of UIActivity types.  Well, the optional is just so we can set it to nil if we don&#8217;t have out own custom UIActivity types.  Since the original writing of this article, this API has been updated, it now is an optional array of UIActivity types, instead of the previous Optional Array of AnyObject.</p>
<p>The second to last line is a bit interesting.  A UIPopoverPresentationController is a way to show popovers on an iPad.  Without this or the popoverPresentationController&#8217;s barButtonItem being set, when a popover is generated, it won&#8217;t know what view created it, or where to point the little arrow that says what button brought it, and will cause a crash.  Setting the sourceView or the barButtonItem properties fix this issue.  This doesn&#8217;t matter on an iPhone, it will just show like normal, and the popoverPresentationController property will just return nil in that Optional Chaining statement.</p>
<h2>Excluding Built In Activities</h2>
<p>So, there are some activities that may not make sense for your app.  How do you explicitly exclude them?  Well, UIActivityViewController has a property that takes an array of the built in UIActivityTypes that you don&#8217;t want.  For this example, we are sharing a snippet of text and a URL.  That sounds like prime Vimeo content, right?  Yeah, probably not.</p>
<p>You don&#8217;t necessarily have to exclude everything that doesn&#8217;t make sense for your app though.  With the code in the last section alone, without explicitly excluding anything, there were several services not listed that wouldn&#8217;t make sense.  What was available was:  Airdrop, Message, Mail, Twitter, Facebook, Add to Reading List, and Copy.  There was no Vimeo or Flickr to be seen.  You can see a great chart on <a title="NSHipster (@NSHipster) | Twitter" href="https://twitter.com/NSHipster">NSHipster&#8217;s</a> Article <a title="UIActivityViewController - NSHipster" href="http://nshipster.com/uiactivityviewcontroller/">UIActivityViewController</a> that shows what data types are supported for each of the built inUIActivityTypes.  The article itself is about the Objective-C form of this class, but much of the information is the same.</p>
<p>For this share though, we are sharing a String of text and an NSURL.  I guess we could Airdrop that, or send it to the reading list, but I think it makes more sense to just share it directly with messages, twitter, etc.  Copy would make sense if we needed to copy whatever is shared to an app that doesn&#8217;t have it&#8217;s own extension yet, so we&#8217;ll leave that in.</p>
<p>All we do is create an array of the UIActivity.ActivityTypes that we do not want to see, and assign that to our UIActivityViewController&#8217;s excludedActivityTypes property.  We would modify our code above like so:</p>
<pre class="lang:swift decode:true ">@IBAction func shareButtonClicked(sender: UIButton) {
    let textToShare = "Swift is awesome!  Check out this website about it!"

    if let myWebsite = NSURL(string: "http://www.codingexplorer.com/") {
        let objectsToShare = [textToShare, myWebsite]
        let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

        //New Excluded Activities Code
        activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList]
        //

        activityVC.popoverPresentationController?.sourceView = sender
        self.presentViewController(activityVC, animated: true, completion: nil)
    }
}</pre>
<p>Then just run that, and you get your small UIActivityViewController shown without the AirDrop section, or the &#8220;Add to Reading List&#8221; action.</p>
<h2>Preparing for Custom Share and Action Extensions</h2>
<p>You don&#8217;t have to do a thing.</p>
<p>With my code above, I could scroll over on UIActivityViewController&#8217;s share section, and use other custom share extensions like Instapaper or Evernote.  I didn&#8217;t have to do a thing.  As a user, you just click the more button to show the ones you want in the share sheet.  As a developer, you don&#8217;t have to do anything to your UIActivityViewController to show custom Share and Action Extensions.</p>
<h2>Conclusion</h2>
<p>Apple made sharing from your apps incredibly easy with the addition of UIActivityViewController.  All you need to do is create an Array of whatever you want to share, give it to a UIActivityViewController initializer, and then present that ViewController.  Really simple.</p>
<p>If you want to see another take on how to do this, check out <a title="David Owens (@dvdowns) | Twitter" href="https://twitter.com/dvdowns">David Owens&#8217;s</a> article <a title="UIActivityViewController (Share Sheet) with Swift | @dvdowns" href="http://www.dvdowns.com/uiactivityviewcontroller/">UIActivityViewController (Share Sheet) with Swift</a>.</p>
<p>Also, if you do want to know how to do this in Objective-C, you can see my previous post <a title="Add sharing to your app via UIActivityViewController" href="http://www.codingexplorer.com/add-sharing-to-your-app-via-uiactivityviewcontroller/">Add sharing to your app via UIActivityViewController</a>.  You can also see there the how to add the sharing button and a list of the available built in UIActivityTypes.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="UIActivityViewController Class Reference" href="https://developer.apple.com/library/ios/documentation/Uikit/reference/UIActivityViewController_Class/index.html">UIActivityViewController Class Reference — Apple Inc.</a></li>
<li><a title="UIActivityViewController - NSHipster" href="http://nshipster.com/uiactivityviewcontroller/">UIActivityViewController — NSHipster</a></li>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-UIActivityViewControllerSwift">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/sharing-swift-app-uiactivityviewcontroller/">Add sharing to your Swift app via UIActivityViewController</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Execution States for a Swift iOS App</title>
		<link>https://www.codingexplorer.com/execution-states-swift-ios-app/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 31 Oct 2014 15:07:56 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=670</guid>

					<description><![CDATA[<p>Time to start moving away from pure Swift posts, and start talking about making iOS apps.  Though we will be talking about doing so with Swift, of course.  Today we are going to talk about the Five Execution states of an iOS app.  The iOS operating system itself changes which state your app is in, and [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/execution-states-swift-ios-app/">Execution States for a Swift iOS App</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Time to start moving away from pure Swift posts, and start talking about making iOS apps.  Though we will be talking about doing so <em>with</em> Swift, of course.  Today we are going to talk about the Five Execution states of an iOS app.  The iOS operating system itself changes which state your app is in, and gives you a chance to make appropriate changes during most of the transitions.<br />
<span id="more-670"></span></p>
<h2>The Five Execution States of an iOS App</h2>
<p>Below I have included a small table describing the five execution states for an iOS app.  The &#8220;Ground&#8221; collumn describe whether the app is in the <strong>Fore</strong>ground or the <strong>Back</strong>ground in that execution state.  The &#8220;Code&#8221; Column says whetehr that state is allowed to run code, or if the iOS operating system disallows it.  Finally the &#8220;Events&#8221; column describes whether the app can respond to events like touches or accelerometer events (like shaking the phone).</p>
<table border="1">
<tbody>
<tr>
<td style="text-align: left;"><strong>State</strong></td>
<td style="text-align: center;"><strong>Ground</strong></td>
<td style="text-align: center;"><strong>Code</strong></td>
<td style="text-align: center;"><strong>Events</strong></td>
<td style="text-align: center;"><strong>Notes</strong></td>
</tr>
<tr>
<td><strong>Not Running</strong></td>
<td style="text-align: center;">N/A</td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td>App was either terminated or just hasn&#8217;t been launched.</td>
</tr>
<tr>
<td><strong>Suspended</strong></td>
<td style="text-align: center;">Back</td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td>App is still in memory.</td>
</tr>
<tr>
<td><strong>Background</strong></td>
<td style="text-align: center;">Back</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;"></td>
<td>App is running in background.  Can be launched to this mode by system.</td>
</tr>
<tr>
<td><strong>Inactive</strong></td>
<td style="text-align: center;">Fore</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;"></td>
<td>Transitional state.  App is either going to or coming from Active State.</td>
</tr>
<tr>
<td><strong>Active</strong></td>
<td style="text-align: center;">Fore</td>
<td style="text-align: center;">X</td>
<td style="text-align: center;">X</td>
<td>App is onscreen and running.</td>
</tr>
</tbody>
</table>
<h3>Not Running</h3>
<p>The simplest state your app can be in.  It&#8217;s just not doing anything.   Your iOS app can get into this execution state by the app being terminated (either by the system or by the user (by swiping it out of the multitasking pane), or by it just not being launched.  This is definitely the case for when the app is first downloaded.  It probably is also after a system reboot, but I am not certain of this yet (I could understand if it might load apps into memory that were before a reboot, but I do not know if it does).</p>
<p><strong>Entrances:</strong>  Suspended State or never being launched</p>
<p><strong>Exits:</strong>  Inactive or Background</p>
<h3>Suspended</h3>
<p>This is the state that your app is usually in when in the background.  The app is still in memory, so it makes it easier to bring back to the Active State, but it is not running code so it does not affect battery life.  When the system is low on memory, the app can be terminated from this execution state and moved to the Not Running state.</p>
<p><strong>Entrances:</strong>  Background</p>
<p><strong>Exits:</strong>  Background or Not Running</p>
<h3>Background</h3>
<p>This mode is where your app has been moved to the background, but is still able to run code.  Your app can be launched directly to this mode if you ask the system to.  This is may be from getting a push notification, such as if a podcast app was to download an episode so it is ready for the user later.  Otherwise, the app is temporarily put into the Background execution state when it is removed from the foreground, giving you a little time to clean things up before the app is Suspended.</p>
<p><strong>Entrances:</strong>  Not Running, Inactive, or Suspended</p>
<p><strong>Exits:</strong>  Inactive or Suspended</p>
<h3>Inactive</h3>
<p>This state is generally just a transitional state.  The only state that has access to the Active state is the Inactive state.  To be in the Inactive state, your app is either becoming Active, or leaving the Active state to move to the background.  It can run some code, but does not respond to touch or other events yet.  This state can also be entered into if there is a system interruption, such as when the user receives a phone call.</p>
<p><strong>Entrances:</strong>  Not Running, Background, or Active</p>
<p><strong>Exits:</strong>  Background or Active</p>
<h3>Active</h3>
<p>This is the main execution state your app will be in when it is onscreen.  If you are touching it and it is responding, it is in the Active state.  In this state you can run code and respond to events.  The only way to go to or from the Active state is through the Inactive state.  If your app is not running, the path to get to the Active state is:</p>
<p>Not Running → Inactive → Active</p>
<p>If your app is Suspended, then the path to active is:</p>
<p>Suspended → Background → Inactive → Active.</p>
<p>When you press the home button, or switch to another app, your app is Suspended.</p>
<p>The path from Active to Suspended is:</p>
<p>Active → Inactive → Background → Suspended</p>
<p>As you can see from all of these different paths, the Active state can only be transitioned to or from the Inactive state.</p>
<p><strong>Entrances:</strong>  Inactive</p>
<p><strong>Exits:</strong>  Inactive</p>
<h2>Handling Execution State Transitions</h2>
<p>So, how do you handle these transitions and get your app ready for the next state it is going to?  There are methods called in your app&#8217;s AppDelegate.swift file for several of these transitions.  Also, each of these methods has an associated notification posted shortly after their associated methods are called.</p>
<h3 class="p1"><span class="s2">applicationWillResignActive(application: </span><span class="s3">UIApplication</span><span class="s2">)</span></h3>
<p class="p1">This method is triggered from the transition from Active to Inactive.  In this method, you should pause any tasks that were running in the foreground.  If you have played a game and been interrupted by receiving a phone call, you will usually come back to the game in some sort of paused state.  Usually you would have to press the pause button manually, but well made games that are time based usually pause your game automatically when this happens.  This method is what allows them to do this, or its associated Notification.</p>
<p class="p1"><strong>Associated Notification:</strong> UIApplicationWillResignActiveNotification</p>
<h3 class="p1"><span class="s2">applicationDidBecomeActive(application: </span><span class="s3">UIApplication</span><span class="s2">)</span></h3>
<p class="p1">This is the counterpart to the above method.  This method is triggered on the transition from the Inactive to the Active State.  Here you basically undo anything you did in applicationWillResignActive, at least when appropriate.  Some games I could understand unpausing the game when you come back, but most I think should stay paused and allow the user to manually unpause, to give them more of a chance to respond to whatever is happing in the game after it is unpaused.  If your app was in the Background, you would probably want to update the user interface here if appropriate (like if a social networking app grabbed new data in the Background that affects what should be onscreen).</p>
<p class="p1"><strong>Associated Notification:</strong> UIApplicationDidBecomeActiveNotification</p>
<h3 class="p1"><span class="s2">applicationDidEnterBackground(application: </span><span class="s3">UIApplication</span><span class="s2">)</span></h3>
<p class="p1">This method is triggered on the transition from Inactive to Background.  You should probably save user state to disk here, if that is important to your app.  After your app is put into the Background, unless you have requested background execution privileges, your app will be Suspended shortly thereafter.  When it is Suspended, the system can terminate your app.  When it does so, you are not alerted, and no method is called.  That is why you should save your state here in this method, because it will probably be your last chance before a termination.</p>
<p class="p1">You could also release shared resources (like the Address Book, or a file) or shut down timers that were running in your application here as well.</p>
<p class="p1"><strong>Associated Notification:</strong> UIApplicationDidEnterBackgroundNotification</p>
<h3 class="p1"><span class="s2">applicationWillEnterForeground(application: </span><span class="s3">UIApplication</span><span class="s2">)</span></h3>
<p class="p1">This method is triggered on the transition from the Background state to Inactive.  In general you should undo anything you did in applicationDidEnterBackground here.  If you shut down timers or released resources, time to start the timers back up or attach to those resources again.</p>
<p class="p1"><strong>Associated Notification:</strong> UIApplicationWillEnterForegroundNotification</p>
<h3 class="p1"><span class="s1">application(application: </span><span class="s2">UIApplication</span><span class="s1">, didFinishLaunchingWithOptions launchOptions: [</span><span class="s2">NSObject</span><span class="s1"> : </span><span class="s2">AnyObject</span><span class="s1">]?) -&gt; </span><span class="s2">Bool</span></h3>
<p class="p1">This method is called when you app is first launched after a termination.  I have yet to find something explicitly saying in which state this happens, or at what transition.  The UIApplicationDelegate Protocol Reference says that &#8220;This method is called after state restoration has occurred but before your app&#8217;s window and other UI have been presented.  At some point after this method returns, the system calls another of your app delegate&#8217;s methods to move the state to the Active (foreground) state or the Background state.&#8221;  As such, it appears to be somewhere around the transition from either Not Running to Inactive, or Not Running to Background transition (depending on whether the app is meant to open to the foreground or background).</p>
<p class="p1"><strong>Associated Notification:</strong> UIApplicationDidFinishLaunchingNotification</p>
<h3 class="p1"><span class="s1">applicationWillTerminate(application: </span><span class="s2">UIApplication</span><span class="s1">)</span></h3>
<p class="p1">This method is called on the transition from Background to Not Running.  If the app is in the Background state, and the app is instructed to terminate (from the system or user), this method is called.  It is not called if the app is terminated while in the Suspended state.  You can save state here if you which, but since it is not called for apps in the Suspended state, it is probably best to save state in the applicationDidEnterBackground method.</p>
<p class="p1"><strong>Associated Notification:</strong> UIApplicationWillTerminateNotification</p>
<h2>Conclusion</h2>
<p>Thus begins our trek from pure Swift to the use of Cocoa Touch to make your iOS apps.  Of course, we will be doing so in Swift, and covering new pure Swift topics as they come up, or I learn something particularly new (to me) that I think should be shared.  I still have a few pure Swift topics on the docket though, but they will be interspersed with topics about iOS app development, like our discussion today.</p>
<p>While you may not interact with all of them in every app, you should still know about the five execution states for an iOS app.  Even in my simple <a title="PregTracker - The Pregnancy Tracker AppCoding Explorer Apps" href="http://apps.codingexplorer.com/pregtracker/">PregTracker app</a>, I still had to handle updating the UI when the app switched from Suspended to Active.  I found that sometimes when I opened the app, the main page would update the days along label, and sometimes it wouldn&#8217;t.  I could force it to by going to another page and coming back, but that&#8217;s a terrible way to update the screen.  I did not know about the five execution states at the time, but I soon found out.  The times it did update when I opened the app, it was because the app needed to be relaunched, and thus it would call viewWillAppear which had my update code in it.  However, the times it did not update when I opened the app, it turned out, were when the app had been Suspended, and was becoming active again.  It didn&#8217;t call viewWillAppear when becoming active again, so the update code wasn&#8217;t called.  I had this view controller subscribe to the UIApplicationWillEnterForegroundNotification (a notification called shortly after the similarly named method above), and call my update code when it received this notification.  You can read about how I did this in Objective-C in my post <a title="Updating an app when returning from background in iOS" href="http://www.codingexplorer.com/updating-an-app-when-returning-from-background-in-ios/">Updating an app when returning from background in iOS</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="App Programming Guide for iOS: The App Life Cycle" href="https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/TheAppLifeCycle/TheAppLifeCycle.html#//apple_ref/doc/uid/TP40007072-CH2-SW3">App Programming Guide for iOS: The App Life Cycle — Apple Inc.</a></li>
<li><a title="UIApplicationDelegate Protocol Reference" href="https://developer.apple.com/library/ios/documentation/uikit/reference/uiapplicationdelegate_protocol/">UIApplicationDelegate Protocol Reference — Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/execution-states-swift-ios-app/">Execution States for a Swift iOS App</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Generic Types in Swift</title>
		<link>https://www.codingexplorer.com/generic-types-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 28 Oct 2014 19:34:36 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=657</guid>

					<description><![CDATA[<p>We have previously discussed generic functions on this blog in the post Generic Functions in Swift.  There is one more aspect to generics in Swift that we have not covered yet, Generic types.  Generic types let you write a named type (class, enumeration, or structure) that can accommodate different types in its implementation. Now, that just [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/generic-types-swift/">Generic Types in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>We have previously discussed generic functions on this blog in the post <a title="Generic Functions in Swift" href="http://www.codingexplorer.com/generic-functions-in-swift/">Generic Functions in Swift</a>.  There is one more aspect to generics in Swift that we have not covered yet, Generic types.  Generic types let you write a named type (class, enumeration, or structure) that can accommodate different types in its implementation.</p>
<p>Now, that just sounds silly right there, why would you want to handle other types in your type?  Well, the main and most predominant reason is for collections.  The best example of this, is the built in Array and Dictionary types.  The shorthand is a lot more readable, and is the recommended way to create Arrays and Dictionaries, but really, [Int] and [String : Int] are actually Array&lt;Int&gt; and Dictionary&lt;String, Int&gt; under the hood.  See those angle brackets?  Yep, those are the same kind of angle brackets used in generic functions.<br />
<span id="more-657"></span></p>
<h2>Avoid Repetition by using Generic Types</h2>
<p>Let&#8217;s say we want a type that can store an array of Integers, and then lets us read one element of that array at random, one way to do that would be like this:</p>
<pre class="lang:swift decode:true">struct RandomIntBag {
    let bag: [Int]
    
    func get() -&gt; Int {
        //Random index less than length of array
        let randomIndex = Int(arc4random_uniform(UInt32(bag.count)))
        
        return bag[randomIndex]
    }
}</pre>
<p>Now, this code does have one major flaw.  If you give it an empty array, and try to use the get method, it will crash.  However, adding the safety code to this muddies up the example.  Really, the get method should probably return an optional Int, but for now, let&#8217;s just dictate that you must never give this an empty array.</p>
<p>Anyway, that definitely gets the job done.  We generate the random number with a C function named arc4random_uniform.  Unfortunately it takes and returns a UInt32, so we have to do a few conversions to let it work with our array index and count.  It will return a random number less than the argument given, in this case a UInt32 version of the bag&#8217;s count property (which is natively a Swift Int).  We then just return whatever is at that random index that we just generated.</p>
<p>Now, what if we wanted similar functionality for a Swift String?  Well we would have to make a RandomStringBag, of course!  It would look like this:</p>
<pre class="lang:swift decode:true">struct RandomStringBag {
    let bag: [String]
    
    func get() -&gt; String {
        //Random index less than length of array
        let randomIndex = Int(arc4random_uniform(UInt32(bag.count)))
        
        return bag[randomIndex]
    }
}</pre>
<p>Now&#8230; that looks awfully similar to our RandomIntBag, doesn&#8217;t it?  To further illustrate that, these are the only lines that have changed inside their respective structure definitions:</p>
<pre class="lang:default decode:true">let bag: [Int]
let bag: [String]

func get() -&gt; Int {
func get() -&gt; String {</pre>
<p>Only the type of the array and the return type of the get method actually changed.  They both hold Swift Arrays underneath, so all of the code inside of the get method is completely the same between them.  Looks like a great time to use generics!</p>
<p>As such, behold the RandomBag:</p>
<pre class="lang:swift decode:true">struct RandomBag&lt;T&gt; {
    let bag: [T]
    
    func get() -&gt; T {
        //Random index less than length of array
        let randomIndex = Int(arc4random_uniform(UInt32(bag.count)))
        
        return bag[randomIndex]
    }
}</pre>
<p>Now you just create a randomBag with an array of whatever type you want, and then get your random value from the get method:</p>
<pre class="lang:swift decode:true">let test = RandomBag(bag: [7,891,894,121,5189,514,42])

test.get()   //Output: 891
test.get()   //Output: 42</pre>
<p>Of course, since this is random, obviously the values you get out will probably be different than this example.</p>
<p>Now that this is a generic type, we could even throw custom classes in there.  Maybe you&#8217;re writing an RPG game, and each area the player is in has a set of monsters that they would battle during a random encounter.  You just give it an array of that custom Monster type, complete with whatever information you need for that battle.</p>
<h2>Conclusion</h2>
<p>While Generic Types are very useful, since they are the very basis of Swift&#8217;s Array and Dictionary type, I personally am having trouble figuring out a use for them outside of implementing other collection types.</p>
<p>Apple&#8217;s iBook uses them to create a Stack type collection (which is basically an array where you can only append or read new data from the top, so it is Last-In-First-Out, or LIFO), as well as a Collection protocol to explain other aspects of the use of Generics in Swift.  A queue data type could also make sense as well, which is similar to the stack, but you can add elements to only one end, and remove them from the other, like the line many of us wait in to get our new iPhones, so this is First-In-First-Out, or FIFO).</p>
<p>Nonetheless though, those are both collections.  One non-collection use for generic types I&#8217;ve found is creating a Factory type that can generate a new object of whatever type you specify to the generic type.  Especially with the addition of Failable Initializers in Swift 1.1, Swift is moving away from the use of Factory types, so I decided not to show an example of that.</p>
<p>If you need a collection type that is not available in vanilla Swift like the Stack or the Queue, or if you just have a completely novel type of collection that you need, Swift&#8217;s Generic Types are the tool for the job.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftGenericTypes">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Creating Random Numbers in Swift [iOS developer:tips];" href="http://iosdevelopertips.com/swift-code/random-numbers-swift.html">Creating Random Numbers in Swift &#8211; [iOS developer:tips];</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/generic-types-swift/">Generic Types in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Operator Overloading — Tailor Swift To Your Needs</title>
		<link>https://www.codingexplorer.com/swift-operator-overloading/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 13 Oct 2014 18:35:09 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=612</guid>

					<description><![CDATA[<p>Sorry, but I have been waiting for months to make this pun.  So today, we are going to talk about Operator overloading in Swift.  This tool is very useful, but quite dangerous as well.  The &#8220;With great power comes great responsibility,&#8221; quote is very appropriate for operator overloading.  It can make your code a lot [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-operator-overloading/">Operator Overloading — Tailor Swift To Your Needs</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Sorry, but I have been waiting for months to make this pun.  So today, we are going to talk about Operator overloading in Swift.  This tool is very useful, but quite dangerous as well.  The &#8220;With great power comes great responsibility,&#8221; quote is very appropriate for operator overloading.  It can make your code a lot more concise, making even a function call seem like a 3-hour long lecture.  But with that, you can also make the code nigh-unreadable to anybody that is new to your code.</p>
<p>Be very careful with this tool, and use it where it make sense, such as how &#8220;adding&#8221; two Swift Strings together makes a new string with one string first, then the other afterwards.  You can make the addition operator print to the screen, make a network request, play music, or whatever else you could write a function for, but doing any of those would be a terrible idea in production code.  You should do only what is necessary for the operator and nothing else.  If you need different things like those, make an appropriately named function that makes it obvious that it will make a network request.</p>
<p>Whenever you think of whether to use operator overloading, you have to ponder whether it helps your code anymore than a simple function call.  The function call may be longer, but it is a whole lot more expressive as to what it does (if named appropriately).  If it looks like you are adding, subtracting, checking equality, or whatever else the built-in operators do though, and you do it enough in your code, Swift&#8217;s operator overloading may be the right tool for the job.<br />
<span id="more-612"></span></p>
<h2>Operator Overloading</h2>
<p>You should only use operator overloading in a way that is consistent with how the operator is normally used in Swift.  Here is an example I thought of that could make sense, though there are still some pitfalls with it.  Let&#8217;s say we want to find the amount of time between two Date objects.  It would make sense to get that via &#8220;laterDate &#8211; initialDate&#8221; right?  So let&#8217;s do that:</p>
<pre class="lang:swift decode:true">extension Date {
    static func - (left: Date, right: Date) -&gt; DateComponents {
        Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second],
                                        from: right,
                                        to: left)
    }
}
</pre>
<p>In this case, I chose the Calendar.Components of year, month, day, hour, minute, and second as the components to use in this subtraction.  Herein lies ones of the pitfalls.  There are several other Components I could choose.  If I just wanted to know the weeks between something, I could put that in instead for this.  Nonetheless, using these units give us what we would want in most calendrical calculations.  The next line just creates the DateComponents object using components:from:to: from the currentCalendar.  We&#8217;re taking advantage of the fact that a single line of code that returns something can be used without explicitly writing return, because it is pretty clear to the compiler that a function that returns a date components being the only thing called in a function that also returns DateComponents would simply want to forward that return.</p>
<p>An operator used between two values is called an <strong>infix</strong> operator.  There are two other overloadable types of operators known as <strong>prefix</strong> and <strong>postfix</strong>, like the old ++i and i++ operators of yore.</p>
<p>As you can see from the top, this is just a function in Swift, but instead of a text name, we have a symbol as the name.  We specify the types of inputs for the left and right parts of the expression, and then specify the return type, which for this calculation should be an DateComponents object.  Now we can use it like this:</p>
<pre class="lang:swift decode:true">let initialDate = Date()

let components = DateComponents(year: 1, month: 5, minute: 42)

let laterDate = Calendar.current.date(byAdding: components, to: initialDate)!

//Test the overloaded operator
difference = laterDate - initialDate

//Results
print(difference.year)    //Outputs: "1"
print(difference.month)   //Outputs: "5"
print(difference.day)     //Outputs: "0"
print(difference.hour)    //Outputs: "0"
print(difference.minute)  //Outputs: "42"
print(difference.second)  //Outputs: "0"</pre>
<p>There was a bit of setup there, but most of it should be pretty easy to understand.  We first create an initial date, which has the value of the moment the Date object was created.  Then there&#8217;s an DateComponents object that has its year, month, and minute values set.  Then the laterDate constant is made, using Calendar&#8217;s dateByAddingComponents method, so that makes a value 1 year, 5 months, and 42 minutes in the future.  Then we actually test our new capability for the &#8221; &#8211; &#8221; operator.  When we look at the components of the result of our subtraction, you can see it has the correct value for the year, month, and minute value for exactly how far in the future it was.</p>
<p>I think that this function is a marginally okay use of operator overloading.  It is using the subtraction operator how it is normally used in math.  However, it hides several assumptions.  I already mentioned that it uses certain Calendar.Components, but not all of them.  Secondly, it uses Calendar&#8217;s current variable.  I think this makes sense, but it is nonetheless hidden.</p>
<p>If we just use the normal function call that is behind our overloaded operator, you can clearly see what calendar it is using and which flags you want.  That is why I only say that this is a marginally okay use of operator overloading.  It makes sense, but it hides those assumptions from the reader, making them have to look up the operator overloading function to see what assumptions are made.</p>
<h2>The Equatable Protocol</h2>
<p>There are a few places in Swift where operator overloading is actually encouraged.  If you want to be able to compare your custom class with the &#8221; == &#8221; operator, you will have to overload it.  If you are going to implement this, your class should probably adopt the Equatable protocol.  The Equatable protocol is used often with Generic functions (you can read more about them here:  <a title="Generic Functions in Swift" href="http://www.codingexplorer.com/generic-functions-in-swift/">Generic Functions in Swift</a>), when it will need to check for equality inside.  If you do, you only need to implement the &#8221; == &#8221; operator, you get the != for free (since it is basically just negating the &#8221; == &#8221; operator&#8217;s answer.</p>
<p>The way you overload the &#8221; == &#8221; operator is the same as with any other infix operator, like what we did above with the &#8221; &#8211; &#8221; operator.  Let&#8217;s make a custom type and overload the &#8221; == &#8221; operator below:</p>
<pre class="lang:swift decode:true">//Custom type itself
class Temperature {
    let c: Double

    init(c: Double) {
        self.c = c
    }
}

//Custom Type's Extension
extension Temperature: Equatable {
    static func == (left: Temperature, right: Temperature) -&gt; Bool {
        if left.c == right.c {
            return true
        } else {
            return false
        }
    }
}

//Test
let tempOne = Temperature(c: 15)
let tempTwo = Temperature(c: 35)
let tempThree = Temperature(c: 15)

let oneTwoEquality = (tempOne == tempTwo)       //Stores:   false

let oneThreeEquality = (tempOne == tempThree)   //Stores:   true</pre>
<p>Now we can compare Temperature instances with the &#8221; == &#8221; operator.  When an operator is overloaded, it must be marked as static.  Actually, if I had made this a struct or enum, I wouldn&#8217;t even need the initializer or the operator overloading!  If the parts in it are hashable or equatable, structs and enums can generate those methods themselves, without me needing to explicitly write them.  The same is not extended to classes, and really, this type should&#8217;ve been a struct, but I wanted to show the behavior for a type that didn&#8217;t automatically get those methods when they adopt the protocol.</p>
<p>Another place where operator overloading in Swift is encouraged is with the Comparable protocol.  To conform to the Comparable protocol you must implement an operator function for the &#8221; &lt; &#8221; operator, as well as conform to the Equatable protocol.  With you implementing == and &gt; operators, the compiler can figure out the !=, &lt;, &lt;=, and &gt;= operators for you.  You can see an example of this in my previous post <a title="Generic Functions in Swift" href="http://www.codingexplorer.com/generic-functions-in-swift/">Generic Functions in Swift</a>.  It also has another example of overloading the &#8221; == &#8221; operator.</p>
<h2>Conclusion</h2>
<p>I debated showing the Date subtraction example above, due to how it hides many assumptions about the code being called.  I decided to share it though, because it also highlights what you have to think about when deciding to use operator overloading in Swift.  If you are doing subtraction of dates a lot in your code, always with the same unitFlags, overloading the subtraction operator could make your code a lot more readable.</p>
<p>There are a few operators that you cannot overload, most notably the assignment operator &#8221; = &#8221; (just one equal sign).  Even if you could, I&#8217;m not sure I would want to know the chaos that would be wrought by doing so, considering how much the assignment operator is used.  You can read more about the operators you can&#8217;t overload at <a title="Tammo Freese (@tammofreese) | Twitter" href="https://twitter.com/tammofreese">Tammo Freese</a>&#8216;s article <a title="Facets of Swift, Part 5: Custom Operators — Swift Programming — Medium" href="https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc">Facets of Swift, Part 5: Custom Operators</a>.</p>
<p>Much like <a title="Custom Subscripts in Swift" href="http://www.codingexplorer.com/custom-subscripts-swift/">Custom Subscripts in Swift</a>, this tool is very useful, but very dangerous.  <span style="text-decoration: underline;"><strong>Use it wisely</strong></span>.</p>
<p>In updating this post, there are two very welcome updates to Swift that made the code for the &#8220;-&#8221; operator&#8217;s overload much nicer.  Firstly, that you can use the most common Calendar.Components with their common names (.Year, .Month, etc.) instead of the longer original ones (<span class="crayon-sy">.</span><span class="crayon-v ">YearCalendarUnit, <span class="crayon-sy">.Month</span><span class="crayon-v ">CalendarUnit, etc.).  Secondly, the code used to use the OR operator &#8221; | &#8221; to combine the unit flags.  Now, Swift lets you give it a Swift Set type for options of that sort, which itself can be created with a Swift Array literal.</span></span></p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftOperatorOverloading">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Facets of Swift, Part 5: Custom Operators — Swift Programming — Medium" href="https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc">Facets of Swift, Part 5: Custom Operators — Swift Programming — Medium</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-operator-overloading/">Operator Overloading — Tailor Swift To Your Needs</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Structures in Swift</title>
		<link>https://www.codingexplorer.com/structures-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 09 Oct 2014 18:19:44 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=631</guid>

					<description><![CDATA[<p>We&#8217;ve so far looked at 2 of the 3 named types in Swift with their own dedicated posts.  First was Enumerations in Swift, and later was Classes In Swift — An Introduction.  Now we finally talk about the third one, Structures. Swift Structures are Value Types Let&#8217;s just get that out there right at the [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/structures-swift/">Structures in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>We&#8217;ve so far looked at 2 of the 3 named types in Swift with their own dedicated posts.  First was <a title="Enumerations in Swift" href="http://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a>, and later was <a title="Classes In Swift — An Introduction" href="http://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a>.  Now we finally talk about the third one, Structures.</p>
<h2>Swift Structures are Value Types</h2>
<p>Let&#8217;s just get that out there right at the beginning.  Much like the enumeration, structures are a value type in Swift.  That means that each time a structure is assigned to a constant, assigned to a variable, or passed to a function (which really is just assigning it to a constant (usually)), it is copied.  So if you set the same structure to multiple variables, and then modify one, all of the others will not change, just that one, because each new variable was a copy of the original, not a reference.<br />
<span id="more-631"></span></p>
<h2>Writing a Structure</h2>
<p>Much like classes and enumerations in Swift, this is pretty simple.  Let&#8217;s use a simple example, a point structure that contains an X and a Y coordinate:</p>
<pre class="lang:swift decode:true">struct XYPoint {
    var x: Int
    var y: Int
}</pre>
<p>Nothing particularly special there, it is pretty much exactly the same as a class in how you write it, except that the <span style="color: #bb2ca2;">struct</span> keyword is used.</p>
<p>You can then modify these properties via dot syntax, like so:</p>
<pre class="lang:swift decode:true">var somePoint = XYPoint(x: 1, y: 2)

somePoint.x = 5
print(somePoint.x)  //Outputs:  "5"</pre>
<p>So when we changed the x coordinate to 5, then told the program to print the value of X which correctly showed the new value of 5.  One thing to note here, in Objective-C, you could read from properties inside a structure instance if you wanted (like the width and height values of CGSize).  However, if you tried to set them, you would get an error.  To modify them, you had to create a completely new instance os CGSize with the new values you wanted.   In Swift, now you can change the values of the properties directly with dot syntax.</p>
<h2>Initializers for Structs</h2>
<p>Now, if this is your first time seeing a struct, you my say to me, &#8220;Hey, you skipped a step in the code here, you didn&#8217;t write an initializer yet, and yet you called one.  I thought you did things step-by-step?&#8221;</p>
<p>Well actually, I did do this step by step, I didn&#8217;t write an initializer, the Swift compiler provided one for me.  This is one of the major differences between structs and classes.  In classes, if you have no properties, or all default values specified for them, you got a free empty initializer to create your class.  With structures, you get a free member-wise initializer.  We can of course write our own other designated initializers if you wish, but you get this one for free.  If you do choose to make your own though, you loose the free member-wise initializer.  This appears to be done under the assumption that if you need to do your own custom initializer, there is probably some special setup that needs to be done, so it disallows somebody from circumventing that by using the default member-wise initializer (whether they tried to use it purposefully or by accident).  If you do want to keep the member-wise initializer, but also have your own, Apple&#8217;s iBook suggests writing the initializer via an extension.  You can read more about them in my earlier article:  <a title="Swift Extensions Part 1 — Computed Properties and Initializers" href="http://www.codingexplorer.com/swift-extensions/">Swift Extensions Part 1 — Computed Properties and Initializers</a>.</p>
<p>Also, one thing to note is that I said you could write your own designated initializers.  Structs can only have designated initializers, structs cannot have convenience initializers.  They can have a similar functionality to them by calling different designated initializers.  None of them are marked with the convenience keyword, like classes, though.  If you want to call another initializer from an initializer, you must refer to the other one via dot syntax from self, like so:</p>
<pre class="lang:swift decode:true">init(x: Int, y: Int) {
    self.x = x
    self.y = y
}

//Initializer to make a point on the Y-Axis
init(y inputY: Int) {
    self.init(x: 0, y: inputY)
}</pre>
<p>See how I also had to rewrite the member-wise initializer too?  Calling one initializer from another is called initializer delegation.  Initializer delegation is done for classes as well, but their version is significantly more complex due to class inheritance.  One more thing about initializer delegation for value types, you cannot call <span style="color: #bb2ca2;">self</span>.<span style="color: #bb2ca2;">init</span> from anywhere else in you code, ONLY from other initializers.</p>
<p>You can read more about initializers in my previous article <a title="Class Initializers" href="http://www.codingexplorer.com/class-initializers/">Class Initializers</a>.  It was originally discussing class initializers, but most of it still applies to structures.</p>
<h2>Differences between Classes and Structs</h2>
<p>In Swift, structures are a lot more like classes than they are in C or Objective-C.  Now that I look at the list, what you can do in functions now is basically everything you can add to a type with an extension, like properties, methods, subscripts, initializers, and adopt protocols.  There are a few capabilities though, that structures and classes do not share.</p>
<p>Major differences between Structures and Classes:</p>
<ul>
<li>Structures cannot Inherit from other types.</li>
<li>Classes use type-casting to treat a class as a superclass or subclass, as well as check protocol adoption.  Structs can only use the protocol adoption part.</li>
<li>Structures do not have deinitializers.</li>
<li>Structures cannot have multiple references to the same instance</li>
</ul>
<p>Considering I said that it was a value type at the beginning though, that last point should come as no surprise.  You can type-cast your struct to be of the &#8220;type&#8221; of a protocol it adopts, but since the rest of type-casting relates to subclasses or superclass, those capabilities don&#8217;t apply to structs.</p>
<h2>Mutating Methods in Structures</h2>
<p>We did cover this some already in my previous post <a title="Instance Methods and Type Methods in Swift" href="http://www.codingexplorer.com/instance-methods-and-type-methods-in-swift/">Instance Methods and Type Methods in Swift</a>, but since we&#8217;re making this the struct reference, I figured it would be best to show it here as well, with a different example:</p>
<pre class="lang:swift decode:true">struct RemoteInformation {
    var stringData = ""


    mutating func updateDataFromSomeWebService() {
        stringData = pretendToTalkToWebService()
    }

    func pretendToTalkToWebService() -&gt; String {
        return "I'm new data from a web service!"
    }
}</pre>
<p>There are a few things that I would do different here if it was a production app (not to mention not have it call &#8220;pretendToTalkToWebService&#8221;.  For one, I would probably set stringData to be private(set) variables so that only our updater can write to them.  The example is very simplified to just highlight the mutating behavior, and not to show how to use Swift&#8217;s access controls or actually talk to a web service.  The pretendToTalkToWebService is written just as a normal function, nothing special because it doesn&#8217;t mutate any state of the structure, it just returns something.  The method updateDataFromSomeWebService though, that does rewrite the stringData, so I had to add the <span style="color: #bb2ca2;">mutating</span> keyword.</p>
<p>Sometimes though, it might be helpful to just overwrite the entire struct with a new structure.  We can do that by just setting to the self property with a new instance of a struct, like so:</p>
<pre class="lang:swift decode:true">mutating func clearData() {
    self = RemoteInformation()
}</pre>
<p>In the first snippet, you can see that the property was given a default value.  Since it was, I could use the blank initializer, because it would just assign the default value.  It effectively let me clear the data by just making a whole new one with an empty stringData.  This does seem like it gets around the initializer delegation issue mentioned earlier, but I guess the implication of initializer delegation is that you are calling an initializer of the same instance of your struct, while doing this just creates a completely new struct, and just replaces the original one.</p>
<h2>Conclusion</h2>
<p>So, when should you use a struct vs a class in Swift?  Well, the two major differences that affect this decision most are the value/reference type difference, and the other is that classes can inherit from other ones.</p>
<p>If you want all references to the instance to be talking to the same instance, where any of them can update the properties, and any of the other references will immediately see that change, then a class would be a good candidate.  If you need to take advantage of inheritance and let types be subtypes, like my Message/TextMessage example from a few posts ago, then you would also want a class.</p>
<p>However, if you wanted each instance to be completely independent from the others, and where you would much rather have the internal data copied than just have a reference to it, then you would want a struct.  There is one caveat to this though, many Cocoa APIs need their parameters to be subclasses of NSObject, so you will need a class for types that need to interoperate with the original Cocoa APIs directly.</p>
<p>Apple&#8217;s iBook also mentions that the properties should be value types themselves and thus that they would in turn be copied when the structure is copied (as opposed to copping the reference to an object when copying the struct).  An earlier version of my RemoteInformation example had the value timestamped with an NSDate, which is a sub<strong>class</strong> of NSObject, so that broke that rule.  I did some testing and couldn&#8217;t really find a mutating function in NSDate that would affect this.  Every function that I found that looked like it mutated just returned an entirely new object created from the mutation that would be set as the new reference.  This effectively works like the copy behavior, where while it is technically possible to mutate these classes, no mutating methods were defined and each mutation just spawns an entirely new instance.  Nonetheless though, it wasn&#8217;t really necessary to the example, so I just left it with the stringData property to highlight the mutation.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftStructs">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Value and Reference Types - Swift Blog - Apple Developer" href="https://developer.apple.com/swift/blog/?id=10">Value and Reference Types &#8211; Swift Blog &#8211; Apple Developer</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/structures-swift/">Structures in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Tuples in Swift: Create, Read, and Return</title>
		<link>https://www.codingexplorer.com/tuples-in-swift-create-read-and-return/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 06 Oct 2014 14:05:33 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=619</guid>

					<description><![CDATA[<p>I was looking for a bit of information on Tuples in Swift for an app I was working on, and decided it would be best to gather what I learn into one, easy to access place. Tuples are a compound type in Swift, which basically means that they can hold multiple values.  A compound type [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/tuples-in-swift-create-read-and-return/">Tuples in Swift: Create, Read, and Return</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I was looking for a bit of information on Tuples in Swift for an app I was working on, and decided it would be best to gather what I learn into one, easy to access place.</p>
<p>Tuples are a compound type in Swift, which basically means that they can hold multiple values.  A compound type can either contain what are called &#8220;named types&#8221;, which include classes, structures, and enumerations (also protocols, but since they don&#8217;t store values directly, I felt I should mention them separately), as well as other compound types.  That means a tuple can hold other tuples.  Another compound type a tuple can contain is the &#8220;function type,&#8221; which is a different way of referring to the type that describes closures (specifically the &#8220;() -&gt;() &#8221; style of type, which functions and methods also conform to.  That also goes the other way, that a function type can hold other compound types, like the Tuple, and other closures, which we&#8217;ve seen in my previous post <a title="Closures and Capturing Values in Swift" href="http://www.codingexplorer.com/closures-capturing-values-swift/">Closures and Capturing Values in Swift</a>.</p>
<p>While <em>technically</em> inaccurate, you can conceptually think of Tuples kind of like a class or structure that you can make on the fly, without having to define a full fledged class or structure (nested or otherwise).  According to Apple&#8217;s iBook though, they should probably only be used for temporary values, like to return them from a function.  It doesn&#8217;t go into detail why, but if I had to guess, they were probably optimized for quick creation, at the cost of how it stores them.  Nonetheless, one of the great new capabilities of Swift is multiple return types, and tuples are what Swift uses to achieve this, since they are technically returning a single value (the tuple itself).</p>
<p>One thing people are sometimes curious about tuples is how it is pronounced.  Well, according to <a title="Tuple | Define Tuple at Dictionary.com" href="http://dictionary.reference.com/browse/tuple">Dictionary.com</a>, there are two valid pronunciations.  In dictionary pronunciation code: /ˈtjʊpəl and ˈtʌpəl/.  For anybody curious, ʊ is the sound of the &#8220;oo&#8221; in &#8220;took&#8221;, ə (a schwa) is how the a sounds in &#8220;about&#8221;, and ʌ (a wedge) is the sound of the &#8220;u&#8221; in &#8220;gut.&#8221;  That means that those are pronounced (roughly) as  too-puhl and tuh-puhl, respectively.  I was digging around for examples of where they were from, only to find out both pronunciations happen for those examples as well, but they are basically from the end of words like &#8220;quadruple,&#8221; &#8220;quintuple,&#8221; and &#8220;octuple&#8221; (notice the &#8220;tuple&#8221; at the end of each).  I personally prefer <strong>too-puhl</strong>, myself.</p>
<p>With readers coming from the US, the UK, and many other places, I suppose the pronunciation will vary.  For those that listen to the <a title="Accidental Tech Podcast" href="http://atp.fm/">Accidental Tech Podcast</a>, apparently <a title="Hover | Define Hover at Dictionary.com" href="http://dictionary.reference.com/browse/hover">Dictionary.com</a> agrees with both sides:  huhv-er (/ˈhʌv ər) and hov-er (ˈhɒv-/ ər).  For those of you that don&#8217;t, you really should go check it out.</p>
<p>Anyway though, you didn&#8217;t come here to learn about English phonetics, it&#8217;s time to learn how to use tuples in Swift!</p>
<p><span id="more-619"></span></p>
<h2>Creating a Tuple</h2>
<p>There are a few ways to create tuples.  Technically, I believe this one is called the &#8220;Tuple Pattern&#8221;.  It pretty much looks exactly like an array literal, except with parenthesis (instead of square brackets), and it can take any type (as opposed to the same type in an Array):</p>
<pre class="lang:swift decode:true">let firstHighScore = ("Mary", 9001)</pre>
<p>The above is the easiest way.  There is another way to make a tuple that takes advantage of Swift&#8217;s named parameters.  You will see why this can be helpful a bit later:</p>
<pre class="lang:swift decode:true">let secondHighScore = (name: "James", score: 4096)</pre>
<p>That really is all there is to it.  If this was a struct, you would have to write out the structure somewhere in your code, with its internal properties and the like.  If it were a class, you would even have to write an initializer for it yourself.  With tuples, all you have to do is put the values you want into a pair of parenthesis, with each value separated by commas.  If you really want, you can even name them for later use.</p>
<h2>Reading from a Tuple</h2>
<p>There are several ways to read from a tuple.  Which one you use will depend on the situation where this tuple is being used.  You can use any of them at any time, but there will probably be situations where one will be easier to use than the others.</p>
<p>First, you can bind the tuple&#8217;s contents using some pattern matching:</p>
<pre class="lang:swift decode:true">let (firstName, firstScore) = firstHighScore</pre>
<p>In the case of this one, since we are using pattern matching, you can also use the underscore to ignore a value if you only want some of them.  If we only wanted to read the score from our tuple, you could do the following:</p>
<pre class="lang:swift decode:true">let (_, onlyFirstScore) = firstHighScore</pre>
<p>They are also given very imaginative default names that count up from 0, so you could also write:</p>
<pre class="lang:swift decode:true">let theName = firstHighScore.0
let theScore = firstHighScore.1</pre>
<p>Finally, if you named them when defining the tuple, you can access them that way with more dot-syntax:</p>
<pre class="lang:swift decode:true">let secondName = secondHighScore.name
let secondScore = secondHighScore.score</pre>
<h2>Returning a Tuple from a Function</h2>
<p>This was covered in my previous post <a title="Functions in Swift: Parameters and Return Types" href="http://www.codingexplorer.com/functions-swift-parameters-return-types/">Functions in Swift: Parameters and Return Types</a>, but since this is all about Swift tuples, I&#8217;ll include it here to have it all rounded up in one place.</p>
<p>Here&#8217;s a function that returns our high score:</p>
<pre class="lang:swift decode:true">func getAHighScore() -&gt; (name: String, score: Int) {
    let theName = "Patricia"
    let theScore = 3894
    
    return (theName, theScore)
}</pre>
<p>So there we named what they would be in the function&#8217;s return type, and when we actually created the tuple, we didn&#8217;t even have to name them.  Since both the tuple we actually returned, and the tuple claimed would be returned in the function prototype were both of type (String, Int), the Swift compiler had no issue with it.  If you didn&#8217;t want to name them in the function prototype, that is okay as well, you just have to state the types, so stating the return type specifically as &#8221; (String, Int) &#8221; is also acceptable to the Swift compiler.</p>
<p>If you want to optionally return a tuple, you would just add a question mark after the return type like so:</p>
<pre class="lang:swift decode:true">func maybeGetHighScore() -&gt; (String, Int)? {
    return nil
}</pre>
<p>Of course, what you then get back is an optional, so you will have to unwrap it to use the values now.  You could do so via optional binding like so:</p>
<pre class="lang:swift decode:true">if let possibleScore = maybeGetHighScore() {
    _ = possibleScore.0
    _ = possibleScore.1
} else {
    print("Nothing Here")
}</pre>
<p>If you want to learn a bit more about Swift Optionals, check out my previous post <a title="Swift Optionals – Declaration, Unwrapping, and Binding" href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals – Declaration, Unwrapping, and Binding</a>.</p>
<p>One more interesting thing to note about Tuples and functions, when you have a function that specifies no return value, it actually returns an empty tuple, which is denoted simply as &#8221; () &#8220;, just an open and then close parenthesis (ignore the quotes, they were just to box the symbol to make it more obvious in this post).</p>
<h2>Access Control and Tuples</h2>
<p>Since my posts have been predominantly for illustrating parts of the Swift language and not full blown tutorials (but that will change soon), we haven&#8217;t talked too much about access control since my initial post <a title="Access Control in Swift" href="http://www.codingexplorer.com/access-control-swift/">Access Control in Swift</a>.  When we do get into tutorials, expect to see them a lot more often.</p>
<p>Nonetheless, they do affect Swift&#8217;s tuples as well.  A tuple&#8217;s access level is determined by its constituents, and is not set directly like you would for a property or function.  A tuple&#8217;s access level will be that of its most restrictive component.  So if one type is <strong>private</strong>, and the other is <strong>public</strong>, the tuple&#8217;s access control will be <span style="text-decoration: underline;"><strong>private</strong></span>.</p>
<h2>A Tuple is a Value Type</h2>
<p><strong style="color: #4d4d4f;">Update:</strong><span style="color: #4d4d4f;"> Thanks to a helpful Clang developer, I have been pointed back to a post on Apple&#8217;s Swift Blog:  <a title="Value and Reference Types - Swift Blog - Apple Developer" href="https://developer.apple.com/swift/blog/?id=10">Value and Reference Types &#8211; Swift Blog &#8211; Apple Developer</a>, which does list the Tuple as a value type, alongside struct and enum.  </span></p>
<p>Before I was reminded of the above, I did a test in a playground to see whether it treated a tuple as a value type or not:</p>
<pre class="lang:swift decode:true">var someScore = ("John", 55)

var anotherScore = someScore
anotherScore.0 = "Robert"


print(anotherScore.0)  //Outputs:  "Robert"
print(someScore.0)     //Outputs:  "John"</pre>
<p>The test does pretty conclusively show that <strong>Tuples are value types</strong>.  I assigned someScore to another variable named &#8220;anotherScore&#8221;.  I then changed the value for the name in anotherScore to &#8220;Robert&#8221;.  When I checked what anotherScore&#8217;s name was, it of course said &#8220;Robert&#8221;, but when I checked someScore (the original one) for what name it had, it still had &#8220;John&#8221;.</p>
<h2>Conclusion</h2>
<p>Now you have a good reference about everything Tuple.  These bits were spread around Apple&#8217;s iBook originally, so you would have to go to the sections about tuples themselves for the first part, functions for the next part, and access control for the final part.  It did make sense for them to be in each of those sections, but since we have already talked about those components on this blog previously, we could just round them all up into a single page.</p>
<p>I also wanted to thank Gavin Wiggins (<a title="Gavin Wiggins (@wigging) | Twitter" href="https://twitter.com/wigging">@wigging</a> on Twitter) for an update to the introduction.  I had not explicitly described the tuple as a compound type, which is stated in the Language Reference part near the end of Apple&#8217;s iBook, and he rightfully said that should be clarified.</p>
<p>I did digress a bit about the pronunciation at the beginning, but I found it interesting and thought I would share.  Pronounce it however you like, but don&#8217;t disparage somebody for pronouncing it the other way, because apparently they&#8217;re both acceptable.  To me though, this post was all about too-puhls.</p>
<p>To follow up a bit on what I mentioned in the Access Control section of this post, I am planning on writing more tutorial style posts eventually.  I wanted to cover the more general concepts first to have a starting point, but then I would eventually move into doing tutorials.</p>
<p>If you look at some of my Objective-C posts, I did mini-tutorials about how to do certain things like <a title="Replace Keyboard with UIDatePicker" href="http://www.codingexplorer.com/replace-keyboard-with-uidatepicker/">Replace Keyboard with UIDatePicker</a> and <a title="Add sharing to your app via UIActivityViewController" href="http://www.codingexplorer.com/add-sharing-to-your-app-via-uiactivityviewcontroller/">Add sharing to your app via UIActivityViewController</a>, and you can expect to see similar posts in Swift.  It may be about specific classes like UIActivityViewController there, or it may be a more general post that puts a few different parts together like the keyboard replacing one.  Making some mini-apps to demonstrate other aspects of programming for iOS in Swift is also on the horizon.  I won&#8217;t say how soon you will start seeing these kind of posts (or videos perhaps).  They could come out next week, or in a few months, but they are coming.  <strong>Update:</strong> Actually, some have come by now, such as <a title="Add sharing to your Swift app via UIActivityViewController" href="http://www.codingexplorer.com/sharing-swift-app-uiactivityviewcontroller/">Add sharing to your Swift app via UIActivityViewController</a>, <a title="How to write a WatchKit Counter App in Swift" href="http://www.codingexplorer.com/watchkit-counter-app-in-swift/">How to write a WatchKit Counter App in Swift</a>, and <a title="Hello World! Your first iOS App in Swift" href="http://www.codingexplorer.com/hello-world-first-ios-app-swift/">Hello World! Your first iOS App in Swift</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftTuples">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/tuples-in-swift-create-read-and-return/">Tuples in Swift: Create, Read, and Return</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swift Extensions Part 2 — Nested Types, Subscripts, Protocols</title>
		<link>https://www.codingexplorer.com/swift-extensions-part-2-nested-types-subscripts-protocols/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 02 Oct 2014 14:30:26 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=604</guid>

					<description><![CDATA[<p>Welcome to part 2 of the Swift Extensions posts.  If you haven&#8217;t already, check out the previous post Swift Extensions Part 1 — Computed Properties and Initializers, to learn about those aspects and get an introduction to what Swift extensions are, and why you might want to use them.  The short reason is they let [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-extensions-part-2-nested-types-subscripts-protocols/">Swift Extensions Part 2 — Nested Types, Subscripts, Protocols</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Welcome to part 2 of the Swift Extensions posts.  If you haven&#8217;t already, check out the previous post <a title="Swift Extensions Part 1 — Computed Properties and Initializers" href="http://www.codingexplorer.com/swift-extensions/">Swift Extensions Part 1 — Computed Properties and Initializers</a>, to learn about those aspects and get an introduction to what Swift extensions are, and why you might want to use them.  The short reason is they let you extend a type for which you may not have the source code for, and you may want to do so to make working with that type easier in your own code.</p>
<p>Are the initializers in the main type long with a bunch of options that are unnecessary for your code?  Add your own convenience initializer that only takes the parameters you need to change, and assigns defaults to the parameters you don&#8217;t care about in the real type&#8217;s initializers.  I was making several different UIColor objects in one of my apps, and they never needed alpha changed, so I just hard-coded that to be 1.0 in an Objective-C category (the precursor to Swift extensions).  Of course, this is only really helpful if you call the longer code several times, which was the case for my app.<br />
<span id="more-604"></span></p>
<h2>Methods in Swift Extensions</h2>
<p>So, I&#8217;ve talked about how Objective-C categories and Swift extensions basically add methods to existing types, but I&#8217;ve not actually shown how to add methods themselves yet.  Well, it&#8217;s pretty anticlimactic.  Really, you just combine my previous post and my post about <a title="Instance Methods and Type Methods in Swift" href="http://www.codingexplorer.com/instance-methods-and-type-methods-in-swift/">Instance Methods and Type Methods in Swift</a>, and that&#8217;s about it, but for completeness, here we go:</p>
<pre class="lang:swift decode:true">extension String {
    func printContents() {
        print(self)
    }
}


//Called

"Swift is awesome!".printContents()
//Output:  "Swift is awesome!"</pre>
<p>This is based on, but even simpler than the example listed in the Apple iBook.  In the iBook, they overload Int with a function that takes a closure, and performs that closure as many times as the Int.  This is cool, but this is significantly simpler than anything that uses closures.  You should notice that we call the <span style="color: #bb2ca2;">self</span> keyword, to refer to the instance of that which we are extending, in this case the String itself.</p>
<p>As mentioned in my post about <a title="Instance Methods and Type Methods in Swift" href="http://www.codingexplorer.com/instance-methods-and-type-methods-in-swift/">Instance Methods and Type Methods in Swift</a>, there is something to keep in mind for value types (structures and enumerations).  If you have to change a property or assign to <span style="color: #bb2ca2;">self</span> in a value type, you must preface the function with <span style="color: #bb2ca2;">mutating</span>.  That is no different for extensions.  If you will recall from the post <a title="Swift Strings" href="http://www.codingexplorer.com/swift-strings/">Swift Strings</a>, Swift Strings are actually structures.  As such, they must follow this rule as well.  Let&#8217;s say we wanted to make every string twice as long, maybe for testing auto-layout issues relating to buttons or labels.  We could do something like this:</p>
<pre class="lang:swift decode:true">extension String {
    mutating func doubleString() {
        self = self + self
    }
}

var testString = "Swift is awesome!"
testString.doubleString()
testString.printContents()
//Outputs:  "Swift is awesome!Swift is awesome!"</pre>
<p>See what I did there?  I was about to just do a normal print, and then I remembered that I just wrote something to do that.  Don&#8217;t worry, I&#8217;m not planning to use this in my future posts.  Anyway, we used the <span style="color: #bb2ca2;">mutating</span> keyword on the function, and then assigned the String concatenated with itself, back to itself.</p>
<h2>Nested Types and Subscripts in Swift Extensions</h2>
<p>The easiest way I thought of showing how to add subscripts with extensions was getting the components out of a Date (the day, month, and year).  I also figured the easiest way to delineate between the different components you would want would require a nested type, so let&#8217;s look at both in the same example.</p>
<p>Like the rest of our discussion of extensions, these are pretty simple.  You basically just declare the subscript code and the nested type within an extension block.  The major new thing is the use of <span style="color: #bb2ca2;">self</span> to refer to that which is being extended.  Without further ado, let&#8217;s see an example of nested types and subscripts to extract the year, month, and day from an Date:</p>
<pre class="lang:default decode:true">extension Date {
    enum DateComponent {
        case year,month,day
    }

    subscript(requestedComponent: DateComponent) -&gt; Int {
        switch requestedComponent {
        case .year:
            return Calendar.current.component(.year, from: self)
        case .month:
            return Calendar.current.component(.month, from: self)
        case .day:
            return Calendar.current.component(.day, from: self)
        }
    }
}</pre>
<p>Yes, you can see when I wrote and compiled that.  We create a simple enumeration at the top just signifying year, month, and day called &#8220;DateComponent&#8221;.  We had the subscript accept a value the DateComponent type, and return an Int for whatever the value of that component was.  We then run the requestedComponent through a switch statement to check which component was being requested, and then call a function to get it, and return that result.  We first requested the current calendar from the type property &#8220;current&#8221; of the Calendar type.</p>
<h2>Adopting and Conforming to protocols with an Extension</h2>
<p>Finally here we are.  With everything else we&#8217;ve talked about, now this one is pretty easy.  Let&#8217;s have a protocol that requires a read-only computed property named &#8220;tweet&#8221;.  This property should return an optional String, containing an actual Swift String if it is 280 characters or fewer, or <span style="color: #bb2ca2;">nil</span> otherwise.  The developer could test for this and disable the &#8220;send&#8221; button if the String is too long, or request the user to write a shorter message.  The protocol would look like this:</p>
<pre class="lang:swift decode:true">protocol Tweetable {
    var tweet: String? { get }
}</pre>
<p>Now, the String type would make sense to adopt this protocol, since tweets are Strings anyway.  Here is how we would adopt and then conform to the Tweetable protocol:</p>
<pre class="lang:swift decode:true">extension String: Tweetable {
    
    var tweet: String? {
        if self.characters.count &lt;= 280 {
            return self
        } else {
            return nil
        }
    }
}</pre>
<p>As you can see, it just counts the characters in the String (<span style="color: #bb2ca2;">self</span>, in this case) with the countElements function.  If it is less than or equal to a length of 140 characters, it returns <span style="color: #bb2ca2;">self</span>.  If it is greater than 140 characters, it will return <span style="color: #bb2ca2;">nil</span>.  Pretty simple.</p>
<p>Now, we can just use it via dot syntax on any Swift String variable or constant:</p>
<pre class="lang:swift decode:true">let shortString = "Swift is awesome!"

let longString = "This is a long run-on sentence that keeps going well in excess of 280 characters just to test this tweet property, while imparting no actually relevant or important meaning.  Really, I'm just trying to write a really long String here.  Okay, maybe it is not too far in excess, but a String of 347 characters is good enough for this example, right?"


let shortTweet = shortString.tweet  //Stores:  "Swift is awesome!"
let longTweet = longString.tweet    //Stores:  nil</pre>
<h2>Conclusion</h2>
<p>There you have it, all of the original capabilities of Swift extensions in two posts.  Swift 2 added the ability to extend protocols themselves as well, which you can read about in its own post <a href="http://www.codingexplorer.com/protocol-extensions-in-swift-2/">Protocol Extensions in Swift</a>.  When you are using something in your app for which you do not have the code, be it a built in Cocoa type, or even a third-party framework, extensions are a great tool to customize them to your needs.  Even if you do have the code, you probably don&#8217;t want to go changing the code for a framework that is updated frequently if the addition is really custom to your project.  In that case, making an extension helps you get what you need, and lets you not have to remember to copy it back into the file if you update the framework from GitHub or whatnot later.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftExtensionsSubTypesProtocols">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-extensions-part-2-nested-types-subscripts-protocols/">Swift Extensions Part 2 — Nested Types, Subscripts, Protocols</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swift Extensions Part 1 — Computed Properties and Initializers</title>
		<link>https://www.codingexplorer.com/swift-extensions/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 29 Sep 2014 18:59:46 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=584</guid>

					<description><![CDATA[<p>So, there has been a reason for my most recent choice of topics to discuss.  This isn&#8217;t some grand culmination post, but the topic for today is related to several of the previous topics due to what it can do.  Back in Objective-C, you could extend classes for which you did not have the source [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-extensions/">Swift Extensions Part 1 — Computed Properties and Initializers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So, there has been a reason for my most recent choice of topics to discuss.  This isn&#8217;t some grand culmination post, but the topic for today is related to several of the previous topics due to what it can do.  Back in Objective-C, you could extend classes for which you did not have the source code with something called categories.  If you are curious about Objective-C categories, I wrote about them back when this blog was still about Objective-C in my post <a title="Objective-C Categories" href="http://www.codingexplorer.com/objective-c-categories/">Objective-C Categories</a>.  This post was much earlier in my blogging career, so it may not be as polished as my current posts, so, you have been warned.</p>
<p>Anyway, Objective-C Categories gave you the ability to add additional methods to another class for which you didn&#8217;t have the original source code.  I used this capability in a later Objective-C post <a title="Introduction to UIColor" href="http://www.codingexplorer.com/introduction-to-uicolor/">Introduction to UIColor</a>, to create a category that made it easier to create a UIColor for my purposes.  I didn&#8217;t need to customize alpha (transparency) each time, and I wanted to use color values between 0 and 255 instead of 0.0 and 1.0, so I made a category that translated my 0 to 255 values to their 0.0 to 1.0 equivalents, and hard-coded the alpha to 1.0 (fully opaque).</p>
<p>These are not the same as iOS 8 extensions, such as the Today View Widgets, UIActivityViewController sharing extensions, etc.  We will cover those in a later post.</p>
<p>When you look at the capabilities of Swift Extensions, they are basically doing the same thing as Objective-C categories, adding methods to existing classes.  With one exception, they are all different flavors of methods.<br />
<span id="more-584"></span></p>
<h2>Swift Extensions</h2>
<p>As mentioned above, Swift extensions are basically adding methods to existing type (classes, structures, and enumerations) just in a few different flavors.  Below I will list off what extensions can add to existing types, as well as the accompanying post I wrote to discuss those aspects in detail:</p>
<ul>
<li>Computed Properties — <a title="Computed Properties in Swift" href="http://www.codingexplorer.com/computed-properties-in-swift/">Computed Properties in Swift</a></li>
<li>Instance and type methods — <a title="Instance Methods and Type Methods in Swift" href="http://www.codingexplorer.com/instance-methods-and-type-methods-in-swift/">Instance Methods and Type Methods in Swift</a></li>
<li>Convenience Initializers — <a title="Designated Initializers and Convenience Initializers in Swift" href="http://www.codingexplorer.com/designated-initializers-convenience-initializers-swift/">Designated Initializers and Convenience Initializers in Swift</a> and <a title="Class Initializers" href="http://www.codingexplorer.com/class-initializers/">Class Initializers</a></li>
<li>Subscripts — <a title="Custom Subscripts in Swift" href="http://www.codingexplorer.com/custom-subscripts-swift/">Custom Subscripts in Swift</a></li>
<li>Nested Types — <a title="Using a Nested Type in Swift" href="http://www.codingexplorer.com/using-nested-type-swift/">Using a Nested Type in Swift</a></li>
<li>Protocol Adoption — <a title="Protocols in Swift" href="http://www.codingexplorer.com/protocols-swift/">Protocols in Swift</a></li>
</ul>
<p>Now you may look at that list and, if you&#8217;ve been following along, probably be able to easily see how computed properties, instance/type methods, initializers, and subscripts are basically just adding methods.  If that isn&#8217;t apparent, I would recommend reading the associated sections from the links above.  Each of them (besides instance/type methods themselves) are related a specialized form of a method.  But protocol conformance and nested types?  How are those methods?  Protocol adoption itself has you define properties even!  Well, stored properties can&#8217;t be boiled down to methods, but computed properties can be!  The protocol doesn&#8217;t care whether the property is stored or computed, so you just would have to use them for the protocol.  Nested types though, those surely aren&#8217;t methods.  That much is true, but the only way to access the nested type of an extension is through a method or computed property.  Apple&#8217;s Swift iBook has a great example of using a nested enumeration in an extension describing whether an Int was positive, zero, or negative.  We will cover another example when we get to talking about that part of Swift extensions.  You can create a nested type in your Swift extension, and then use it elsewhere in that extension, or whatever calls the it.</p>
<p>The syntax to create an extension is very similar to creating a type, and it looks a little something like this:</p>
<pre class="lang:swift decode:true">extension UIColor: ImportantProtocol, MoreImportantCustomProtocol {
    //Fill in the blank
}</pre>
<p>So you can see, instead of <span style="color: #bb2ca2;">class</span>, <span style="color: #bb2ca2;">struct</span>, or <span style="color: #bb2ca2;">enum</span>, we use the <span style="color: #bb2ca2;">extension</span> keyword.  Afterwards, we the list of protocols it will adopt (if any).  If you don&#8217;t need new protocols, just declare it without the colon and anything afterwards, so:</p>
<pre class="lang:swift decode:true">extension UIColor {
    //Fill in the blank
}</pre>
<p>Classes can override their superclass&#8217;s implementation of a method, however, extensions <strong>cannot</strong> do similar.  Swift extensions can add new capabilities to a type, but they cannot override anything.  You can add completely new functionality with a very similar name to a method, but it cannot be the same and must be unique, and cannot use the <span style="color: #bb2ca2;">override</span> keyword.</p>
<p>You can add this to the end of any Swift file (outside of the type&#8217;s curly braces) if you wish, or you can create a separate file and have it in your target.  I don&#8217;t know what the best practice is yet, but I will probably do it as a separate file until I find a reason not to.  You do not name extensions like you did in Objective-C, and you do not need to import them in your files (since they will be shared in the same module by default (unless marked as private, of course)).</p>
<h2>Convenience Initializers in Swift Extensions</h2>
<p>I said that on purpose there.  You can only add convenience initializers in Swift extensions, not designated initializers.  These follow the same rules as convenience initializers in a type, that they can call other convenience initializers, but must eventually call a designated initializer of the class it is extending.  You of course must also make sure that all properties are given valid values before initialization is complete.</p>
<p>We will harken back to my Objective-C <a title="Introduction to UIColor" href="http://www.codingexplorer.com/introduction-to-uicolor/">Introduction to UIColor</a> post for this one, and remake a simplified version of my UIColor initializer:</p>
<pre class="lang:swift decode:true">extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        let newRed = CGFloat(red)/255
        let newGreen = CGFloat(green)/255
        let newBlue = CGFloat(blue)/255
        
        self.init(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
    }
}</pre>
<p>It calls the designated initializer for UIColor via <span style="color: #bb2ca2;">self</span>.<span style="color: #bb2ca2;">init</span> at the end, with the Integer components converted into the CGFloats necessary for that initializer.  Similar to my original post, if you want to use something like this, you should put some bounds checking code in the initializer to make sure your newRed, newGreen, and newBlue are between 0 and 1.0 before you call the designated initializer, just to make sure they are valid values.</p>
<h2>Computed Properties in Swift Extensions</h2>
<p>There is something important to know before we go any further.  <strong>Swift extensions cannot add stored properties to a type.</strong>  You can make computed properties, but you cannot store them unless they store via a stored property that is already in the type you are extending (like if you added an extension to a Bool to take the Strings &#8220;Oui&#8221; or &#8220;Non&#8221; and just mapped them back to <span style="color: #bb2ca2;">true</span> and <span style="color: #bb2ca2;">false</span> and stored those as the Bool&#8217;s value).  You also <strong>cannot add property observers to properties that already exist in the type you are extending</strong>.</p>
<p>Let&#8217;s say you were making an app that had stored hashtags without the # symbol.  We want to read them back out with the # symbol prepended, so let&#8217;s add that as a read-only computed property:</p>
<pre class="lang:swift decode:true">extension String {
    var hashtag: String {
        get {
            return "#\(self)"
        }
        set {
            let stringWithoutHashtag = newValue.replacingOccurrences(of: "#", with: String(), options: .literal)
            self = stringWithoutHashtag
        }
    }
}

//Usage
let stringOne = "swift"
let stringTwo = "swiftlang".hashtag     //Can use on literals too

print(stringOne.hashtag)                //Outputs:  "#swift"
print(stringTwo)                        //Outputs:  "#swiftlang"

var justTag = String()

justTag.hashtag = "#iosdev"
print(justTag)                          //Outputs:  "iosdev"</pre>
<p>Using the setter for this one is a bit clunky (I couldn&#8217;t set directly from the declaration of justTag), but you get the point there.  You read from or assign to self for the getter and the setter respectively to use computed properties in a Swift extension.</p>
<h2>Conclusion</h2>
<p>This post is getting a bit long, so we shall cover the other capabilities of Swift extensions in a later post.</p>
<p>Swift extensions are particularly useful for making the built-in Swift or Cocoa types easier to use in the context of your app.  When I started adding some UIColor code to one of my apps, it just got unwieldy to do it all by hand.  I had RGB values in 0 to 255, and I never wanted to change the alpha.  To use the built in type, I had to have (colorComponent/255.0) for each component (or calculate them externally (in my case with a spreadsheet earlier on)) and constantly setting alpha to 1.0.  It was ridiculous and unscalable.  When I added the Objective-C category that the above Swift extension was based on, my code got a lot clearer, showing just what I needed.  It also got safer (in case of a typo of setting a color value above 255) because I also added bounds checking to the category (not depicted above).  Swift extensions are extremely useful and you can bet I&#8217;ll be using them in my code.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftExtensionsInitsProperties">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Any way to replace characters on Swift String? - Stack Overflow" href="http://stackoverflow.com/a/24201206/2775523">Any way to replace characters on Swift String? &#8211; Stack Overflow</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-extensions/">Swift Extensions Part 1 — Computed Properties and Initializers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Instance Methods and Type Methods in Swift</title>
		<link>https://www.codingexplorer.com/instance-methods-and-type-methods-in-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 27 Sep 2014 16:49:09 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=587</guid>

					<description><![CDATA[<p>We touched a bit on this in a previous post Classes In Swift — An Introduction.  To recap what was mentioned in that post, methods are functions that are associated with a type.  In other words, all methods are functions, but not all functions are methods.  Functions can be written outside of the context of a [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/instance-methods-and-type-methods-in-swift/">Instance Methods and Type Methods in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>We touched a bit on this in a previous post <a title="Classes In Swift — An Introduction" href="http://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a>.  To recap what was mentioned in that post, <strong>methods are functions that are associated with a type</strong>.  In other words, all methods are functions, but not all functions are methods.  Functions can be written outside of the context of a type, especially in playgrounds.  I felt it would be best to state that in a post dedicated to them, instead of having it just nestled in the Classes post.  I also have learned of some nuances about them, that there are a few differences between them, particularly in parameter naming.  While I&#8217;m at it, we&#8217;ll quickly cover the idea of type methods as well.<br />
<span id="more-587"></span></p>
<h2>Instance Method External Parameter Name Nuance</h2>
<p>To explain this better, we need a slight history lesson.  In Objective-C, there are many instances where a method name would refer to the first parameter, and the next parameters would have labels describing them as the function call went on.  Here is a particularly common function prototype like that:</p>
<pre class="lang:objc decode:true">- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath</pre>
<p>Good ol&#8217; tableView:didSelectRowAtIndexPath:.  It&#8217;s not as common as cellForRowAtIndexPath:, but that one only takes one parameter, and this is something I wanted to show.  You can see how the &#8220;name&#8221; of the function is &#8220;tableView&#8221;, and it refers to an object of the type (UITableView *), with an internal name of tableView.  The next parameter has an external name &#8220;didSelectRowAtIndexPath:&#8221;, which takes an object of type (NSIndexPath *), with an internal name of &#8220;indexPath&#8221;.</p>
<p>While you would usually never call this function yourself (it is usually something you override when writing a UITableViewDelegate).  Nonetheless, if you did call it, it would look something like this:</p>
<pre class="lang:objc decode:true">[self tableView:myTable didSelectRowAtIndexPath:myIndexPath]</pre>
<p>Again, really, don&#8217;t call that yourself.  Anyway, you can see how the parameter names make this read similar to a sentence.  In this case you are telling the self object, that the tableView named myTable did have a row selected that is at an indexPath named &#8220;myIndexPath.&#8221;</p>
<p>So, what does this look like in Swift?</p>
<pre class="lang:swift decode:true">//Method Prototype
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

//Called
someTableViewDelegate.tableView(myTable, didSelectRowAt: myIndexPath)</pre>
<p>Okay, that isn&#8217;t too surprising, it had an external parameter name of didSelectRowAtIndexPath.</p>
<p>However, what if we delete that external parameter name, and just leave it with the internal parameter name:</p>
<pre class="lang:swift decode:true">//Method Prototype
func tableView(tableView: UITableView, indexPath: NSIndexPath)

//Called
someTableViewDelegate.tableView(myTable, indexPath: myIndexPath)</pre>
<h2>Mutating Properties of Structures and Enumerations</h2>
<p>If you recall, in our discussion about <a title="Protocols in Swift" href="http://www.codingexplorer.com/protocols-swift/">Protocols in Swift</a>, if we wanted to change internal values for structures and enumerations, we had to preface a function that did that with the <span style="color: #bb2ca2;">mutating</span> keyword.  That is actually what you have to do for methods that mutate properties in these value types, so that part of the protocol was just basically extending this part to be visible in the protocol itself.</p>
<p>In the example below, we have made a Person class, with the properties of firstName and lastName.  In it we have a function that will change these values to a new name.  We must preface this function with the <span style="color: #bb2ca2;">mutating</span> keyword for value types, like so:</p>
<pre class="lang:swift decode:true ">struct Person {
    var firstName = ""
    var lastName = ""
    
    mutating func changeFirstName(first: String, last: String) {
        firstName = first
        lastName = last
    }
}</pre>
<p>If we neglect to put the <span style="color: #bb2ca2;">mutating</span> keyword in, we get the error &#8221; Cannot assign to property: &#8216; self &#8216; is immutable&#8221;.  You do not need to do this for reference types (namely, Classes) though, this is only something you have to do for Structures and Enumerations.</p>
<h2>Writing And Calling Type Methods</h2>
<p>Sometimes there may be a function that is not specific to one instance of a class.  In this case, we can use a type method, which means exactly what it sounds like.  It is a method associated with the type, and not a specific instance.</p>
<p>One great example of the use of type methods would be like the C Math library, or more to the point, reimplementing something like that.  We probably would make a class and not a struct, but below I will show both to show the difference in syntax for type methods in value and reference types:</p>
<pre class="lang:swift decode:true">class Math {
    class func absoluteValue(of value: Int) -&gt; Int {
        if value &lt; 0 {
            return (-value)
        } else {
            return value
        }
    }
}

struct MathStruct {
    static func absoluteValue(of value: Int) -&gt; Int {
        if value &lt; 0 {
            return (-value)
        } else {
            return value
        }
    }
}</pre>
<p>You generally declare a method as a Type Method by using the <span style="color: #bb2ca2;">static</span> keyword for both Reference types and Value Type (now).  If you want a subclass of a class to be able to override the Type method, you can use the <span style="color: #bb2ca2;">class</span> keyword instead.  Prior to Swift 1.2, static was only used for value types, and class was only used for reference types, but that is no longer the case.</p>
<p>To call them, you don&#8217;t query a specific instance of an entity, type itself.  You don&#8217;t even need to declare an instance to use type methods, as shown below:</p>
<pre class="lang:swift decode:true">let referenceTypeAnswer =       Math.absoluteValue(of: -5)
let valueTypeAnswer     = MathStruct.absoluteValue(of: -5)</pre>
<p>They are called the exact same way for the value and reference type versions.  As far as calling a type method goes, it doesn&#8217;t matter whether it was written with the <span style="color: #bb2ca2;">class</span> or <span style="color: #bb2ca2;">static</span> keyword.</p>
<p>For another example of using type methods, check out this type method for a Point class:</p>
<pre class="lang:swift decode:true">struct Point {
    var x = 0.0
    var y = 0.0
    
    static func closestToOrigin(_ p1: Point, _ p2: Point) -&gt; Point {
        let p1Distance = p1.distanceFromOrigin()
        
        let p2Distance = p2.distanceFromOrigin()
        
        if p1Distance &lt; p2Distance {
            return p1
        } else {
            return p2
        }
    }
    
    func distanceFromOrigin() -&gt; Double {
        return sqrt((x*x)+(y*y))
    }
    
}


let firstPoint = Point(x: 1.5, y: 3.9)
let secondPoint = Point(x: 49.2, y: 15.9)

let answer = Point.closestToOrigin(firstPoint, secondPoint)
answer.x    //Returns 1.5
answer.y    //Returns 3.9</pre>
<p>The type method closestToOrigin does take instances of the structure, but it itself is a method that can be called from the type&#8217;s context.  It even calls an instance method (distanceFromOrigin) of the Points that are passed in, to let them calculate their own distance from the origin.</p>
<h2>Conclusion</h2>
<p>Methods are a huge part of writing programs in just about any language.  It may seem so fundamental that covering it separate from functions may seem silly.  I felt there were enough nuances to warrant it getting its own post.</p>
<p>Type methods do come in handy occasionally.  I haven&#8217;t used their equivalents very often in other programming languages, but every once in a while a type method or property can be quite useful.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-MethodsTypeMethodsSwift">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/instance-methods-and-type-methods-in-swift/">Instance Methods and Type Methods in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Designated Initializers and Convenience Initializers in Swift</title>
		<link>https://www.codingexplorer.com/designated-initializers-convenience-initializers-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 25 Sep 2014 14:53:53 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[properties]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=577</guid>

					<description><![CDATA[<p>Today we will be learning about another aspect of Class Initializers.  The Swift language has two different types of initializers they are called designated initializers and convenience initializers.  These existed in Objective-C, but a few rules have changed in Swift, and a very helpful keyword was introduced.  We will discuss how designated and convenience initializers are [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/designated-initializers-convenience-initializers-swift/">Designated Initializers and Convenience Initializers in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Today we will be learning about another aspect of <a title="Class Initializers" href="http://www.codingexplorer.com/class-initializers/">Class Initializers</a>.  The Swift language has two different types of initializers they are called designated initializers and convenience initializers.  These existed in Objective-C, but a few rules have changed in Swift, and a very helpful keyword was introduced.  We will discuss how designated and convenience initializers are used, and how they can work together to get your classes ready for use.</p>
<h2>Designated Initializers</h2>
<p>Like most constructs in Swift, designated initializers are aptly named and do exactly what they say they do.  They are the main initializers to be used for a class.  A class must have one designated initializer, but it is not limited to one.  It can have multiple if necessary, but most classes only have one.<br />
<span id="more-577"></span><br />
Let&#8217;s take a look at a designated initializer:</p>
<pre class="lang:swift decode:true">init(sender: String, recipient: String) {
    self.sender = sender
    self.recipient = recipient

    timeStamp = Date()
}</pre>
<p>Does that look a bit familiar?  If you&#8217;ve been following the blog for a while it should, that is the initializer for our Message class used in the previous articles <a title="Classes In Swift — An Introduction" href="http://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a> and <a title="Using a Nested Type in Swift" href="http://www.codingexplorer.com/using-nested-type-swift/">Using a Nested Type in Swift</a>.  That syntax is to create a designated initializer.  Our Message class only had one initializer, so it had to be the designated one.  To create a designated initializer, it is just the <span style="color: #bb2ca2;">init</span> keyword, with the parameters afterwards, and then the code inside the curly braces.</p>
<h2>Convenience Initializers</h2>
<p>Convenience initializers are also aptly named, and they are initializers used to make initialization a bit easier.  Designated initializers tend to set all of the properties up and let the user send in values for each.  A convenience initializer often has some of those hard coded, and thus can take less parameters.  The developer usually write&#8217;s a convenience initializer to set some defaults that are appropriate to a special use case.</p>
<p>The initializer above probably should have been a convenience initializer, since it sets timeStamp without giving the user any input to set one themselves.  Like I said above, I think that designated initializers tend to have parameters for all properties they are setting (unless derived from some of the other parameters).  This is just personal preference though, the above one is perfectly valid as a designated initializer, since we said in those posts that the timeStamp is set when the Message is created.</p>
<p>Nonetheless, let&#8217;s add a convenience initializer to our Swift app.  Let&#8217;s say that this app could also send a message to oneself, to use it as a note perhaps.  In this case, we wouldn&#8217;t need to set the sender and the recipient to different values.  We would only be repeating ourself in the initializer when doing that, so lets write a convenience initializer that takes only one parameter:</p>
<pre class="lang:swift decode:true">convenience init(sender: String) {
    self.init(sender: sender, recipient: sender)
}</pre>
<p>The main difference in their syntax, is that convenience initializers have the <span style="color: #bb2ca2;">convenience</span> keyword before the <span style="color: #bb2ca2;">init</span>.  Otherwise they are exactly the same.  Once inside our convenience initializer that only takes the sender as a parameter, we just give that parameter to the designated initializer as both the sender and the recipient, since this Message is being used more like a note.</p>
<h2>Rules for Designated and Convenience Initializers</h2>
<p>Swift has three rules as to how designated and convenience initializers relate to each other.  Instead of trying to paraphrase them, I&#8217;m just going to quote Apple&#8217;s iBook directly:</p>
<blockquote>
<ol>
<li>A designated initializer must call a designated initializer from its immediate superclass.</li>
<li>A convenience initializer must call another initializer from the same class.</li>
<li>A convenience initializer must ultimately call a designated initializer.</li>
</ol>
<p>Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. <a title="iTunes - Books - The Swift Programming Language by Apple Inc." href="https://itun.es/us/jEUH0.l">https://itun.es/us/jEUH0.l</a></p></blockquote>
<p>So you can see our convenience initializer fulfilled rules 2 and 3.  Our designated initializer was the top class in the hierarchy (the Message class), so there was no superclass initializer to call (for rule 1).  If you recall though, it did have subclasses, like one for a TextMessage, let&#8217;s look at TextMessage&#8217;s designated initializer:</p>
<pre class="lang:swift decode:true">init(content: String, sender: String, recipient: String) {
    self.content = content
    super.init(sender: sender, recipient: recipient)
}</pre>
<p>You can see there, that it fulfills rule 1, calling &#8220;a designated initializer from its immediate superclass.&#8221;  One thing to note, you see that we set our <span style="color: #bb2ca2;">self</span>.content property first, and then we called our superclass&#8217;s designated initializer.  This is in contrast to how it was done in Objective-C (which had you call the superclass&#8217;s initializer first).  <span style="text-decoration: underline;">A Swift class must initialize its own (non-inherited) properties before it calls its superclass&#8217;s designated initializer</span>.  You can then set inherited properties after calling the superclass&#8217;s designated initializer, if you wish.</p>
<p>This appears to be due to how class inheritance works, according to one of the WWDC videos (specifically Intermediate Swift).  For instance, if a superclass calls a method that the subclass overrode, the superclass will actually call the subclass&#8217;s implementation (since it was overridden).  If we didn&#8217;t fully initialize our subclass&#8217;s properties, and that overridden function relied on them, we would have a bit of a problem.</p>
<p>If you are unsure what I am talking about with the <span style="color: #bb2ca2;">self</span>.content setting there, the whole code for these classes is shown in the previous post <a title="Classes In Swift — An Introduction" href="http://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a>.</p>
<p>There is a nuance to these rules.  In rule 2, you see that it just says that a convenience initializer must call another initializer.  It doesn&#8217;t say dedicated initializer there, just any initializer.  If you want, you can have several convenience initializers that handle a small part of the initialization, and just call them in a chain.  However though, you still have to follow rule 3.  If you want to call multiple convenience initializers, they have to eventually lead to one that calls a designated initializer.  Here is an example fulfilling all 3 rules in our TextMessage class:</p>
<pre class="lang:swift decode:true">init(content: String, sender: String, recipient: String) {
    self.content = content
    //Rule 1:  Calling designated Initializer from immediate superclass
    super.init(sender: sender, recipient: recipient)
}

convenience init() {
    //Rule 2:  Calling another initializer in same class
    self.init(content: "")
}

convenience init(content: String) {
    //Rule 2:  Calling another initializer in same class
    self.init(content: content, sender: "Myself")
}

convenience init(content: String, sender: String) {
    //Rule 2 and 3:  Calling the Designated Initializer in same class
    self.init(content: content, sender: sender, recipient: sender)
}</pre>
<p>You can see the no-parameter convenience initializer calls the single parameter convenience initializer with a blank content Swift String.  That convenience initializer then calls the 2 parameter convenience initializer with the provided content String, and sets the sender parameter to the String &#8220;Myself&#8221;.  Finally that convenience initializer calls the designated initializer for this class with the provided content String, and sets the sender and recipient parameters to the provided &#8220;sender&#8221; parameter.  That fulfills rules 2 and 3.  Then there is of course the designated initializer we mentioned earlier that calls its superclass&#8217;s designated initializer, fulfilling rule 1.</p>
<p>Now, you probably would not want to make such a silly chain of convenience initializers, setting each part individually like that, at least not very often.  Nonetheless though, you can, and there are definitely use cases for convenience initializers setting up individual parts.  If nothing else, it lets you write the code for setting those defaults only once, if they must be set in the initializers.</p>
<p>Now, we made that convenience initializer earlier for setting the sender and receiver to be the same for notes, why not make some sort of NoteMessage subclass and call that?  Well&#8230;.</p>
<pre class="lang:swift decode:true">class NoteMessage: Message {
    let content: String

    init(content: String, theUser: String) {
        self.content = content
        super.init(sender: theUser)
        //Error!:  Must call a designated initializer of the superclass 'Message'
    }
}</pre>
<p>Awww&#8230;..  I guess we&#8217;ll have to slog through and set both the sender and receiver ourselves in Message&#8217;s designated initializer.  Remember rule 1, &#8220;A designated initializer must call a <span style="text-decoration: underline;"><strong>designated initializer</strong></span> from its immediate superclass.&#8221;  We tried calling a convenience initializer, and it did not take kindly to that.</p>
<p>I am not entirely sure why you cannot call a superclass&#8217;s convenience initializer in Swift.  Since the convenience initializer for the superclass eventually calls a designated initializer of that superclass, that should have everything fully initialized.  It may be simply that designated initializers just aren&#8217;t allowed to call convenience initializers at all, since doing so in their same class would cause circular calls (designated initializer -&gt; convenience initializer -&gt; designated initializer, etc).  That might be it, but I am not sure.</p>
<p>It might be just to force the programmer to think of what default is appropriate for your class to set to its superclass&#8217;s properties.  In the case of our class, the superclass&#8217;s convenience initializer would have been fine, but that may not always be the case.  In other words, it may not be a technical limitation, but just one to make the programmer think a bit more about how they are initializing their properties.</p>
<p>Or it could just be a limitation of Swift that will be changed later, who knows?  For now though, the rule stands, that &#8220;a designated initializer must call a <strong>designated initializer</strong> from its immediate superclass.&#8221;</p>
<h2>Conclusion</h2>
<p>Designated initializers perform the actual initialization for a class&#8217;s properties.  Convenience initializers let you program defaults into simpler initializers with less input parameters, and they hand off the actual initialization back to the designated initializers.  You don&#8217;t have to have any convenience initializers if you wish, but they are quite useful in certain situations.</p>
<p>I am particularly happy about the addition of the <span style="color: #bb2ca2;">convenience</span> keyword in Swift.  In Objective-C, as far as i know, the only way to know which was the designated initializer was to look in the comments in the header file (assuming you do not have access to the code).  If they did not comment about it, and you don&#8217;t have the code, I think you would just have to guess.  If you had the code, the designated initializer is the one that calls the superclass&#8217;s initializer (similar to rule 1 above).</p>
<p>Clearly marking a convenience initializer as such just makes it easier to know.  In our class, it was rather obvious, but it may not be so obvious for all classes.</p>
<p>I hope you found this article helpful.If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftDesignatedConvenienceInits">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/designated-initializers-convenience-initializers-swift/">Designated Initializers and Convenience Initializers in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swift Property Observers</title>
		<link>https://www.codingexplorer.com/swift-property-observers/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 23 Sep 2014 15:30:58 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[properties]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=568</guid>

					<description><![CDATA[<p>In my previous article Class Initializers, I had mentioned property observers, and glossed over them a bit.  Now we&#8217;ll discuss them in a bit more depth. Why use a Property Observer? Back in Objective-C, if you wanted to do any special handling for setting a property, you would have to override the setter, reimplement the [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-property-observers/">Swift Property Observers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In my previous article <a title="Class Initializers" href="http://www.codingexplorer.com/class-initializers/">Class Initializers</a>, I had mentioned property observers, and glossed over them a bit.  Now we&#8217;ll discuss them in a bit more depth.</p>
<h2>Why use a Property Observer?</h2>
<p>Back in Objective-C, if you wanted to do any special handling for setting a property, you would have to override the setter, reimplement the actual value setting (that was originally done for you), and then add whatever you wanted to do besides that, like posting a notification of a change.  Swift&#8217;s property observers save you from having to reimplement the setter in those cases.</p>
<p>Property Observers are somewhat similar to computed properties.  You can read more about those in my previous article <a title="Computed Properties in Swift" href="http://www.codingexplorer.com/computed-properties-in-swift/">Computed Properties in Swift</a>.  For computed properties, you write custom code for the getter and setter.  For property observers, you write custom code only for setting, for right before (<span style="color: #bb2ca2;">willSet</span>) and right after (<span style="color: #bb2ca2;">didSet</span>).  The main purpose of Swift&#8217;s property observers is to watch for when a property is set.  As such, property observers are only useful for variables (<span style="color: #bb2ca2;">var</span> properties), and cannot be written for constants (<span style="color: #bb2ca2;">let</span> properties).<br />
<span id="more-568"></span></p>
<h2>How to Implement Property Observers</h2>
<p>There are two very appropriately named property observers in Swift: <span style="color: #bb2ca2;">willSet</span>, and <span style="color: #bb2ca2;">didSet</span>.  They are called exactly when you think they would be, right before and right after setting, respectively.  On top of this, they are also implicitly given constants describing the newValue and oldValue respectively.</p>
<ul>
<li><span style="color: #bb2ca2;">willSet</span> comes with a constant parameter that contains the new value, with the default name newValue</li>
<li><span style="color: #bb2ca2;">didSet</span> comes with a constant parameter that contains the old value, with the default name oldValue</li>
</ul>
<p>You can override either of those names, if you wish, but if no name is provided, the defaults are used.</p>
<p>Say we had a Swift String property.  This property is set often in some program, but not always to a different value.  If this String is set to the same value, just let things continue as if nothing happened (because really, not much did).  If the String gets a new value though, we need to post a notification for another class to update based off of that new value.  That is a great time to use Swift&#8217;s property observers!</p>
<p>Here is a declaration of such a Swift String with both property observers implemented with their default parameter names:</p>
<pre class="lang:swift decode:true">var userStatusText: String {

    willSet {
        print("About to set status to:  \(newValue)")
    }

    didSet {
        if userStatusText != oldValue {
            postNewStatusNotification()
        }
    }
}</pre>
<p>This code uses the default names for the new and old value constants by not including a name of its own.  In the <span style="color: #bb2ca2;">willSet</span>, we print out a line saying what we are about to change the status to.  For the <span style="color: #bb2ca2;">didSet</span>, we check if the current value (since this is the <span style="color: #bb2ca2;"><strong><span style="text-decoration: underline;">did</span></strong>Set</span>) of our variable is different from the oldValue that it used to be.</p>
<p>For reference, here is the same thing but with custom names for newValue and oldValue:</p>
<pre class="lang:swift decode:true">var userStatusText: String {

    willSet(incomingStatus) {
        print("About to set status to:  \(incomingStatus)")
    }

    didSet(previousStatus) {
        if userStatusText != previousStatus {
            postNewStatusNotification()
        }
    }
}</pre>
<p>All you do to give it a custom name is write the new name inside parenthesis after the <span style="color: #bb2ca2;">willSet</span> or <span style="color: #bb2ca2;">didSet</span>, somewhat similar to naming parameters in a normal function, though without type information since the type is already stated as part of the property&#8217;s definition.</p>
<p>You do not have to define both property observers if you only need one.  I am just showing both above for reference.</p>
<p>You can reassign to your value within <span style="color: #bb2ca2;">didSet</span> if you really want, and that new value you set will be the final value of the variable.  Doing so does not recursively re-call the property observers.  You might want to do this for some sort of bounds checking perhaps, though if that is a concern, a computed property might be a better choice, since there may be something the could react to the new value that wasn&#8217;t yet bounds checked during the few cycles that it exists in the invalid state (perhaps on a different thread).  It should be called immediately, but I don&#8217;t think I would trust it if that new value needs to be bound checked.  It would be best if we could bound-check in the <span style="color: #bb2ca2;">willSet</span>, test the newValue, and then set it to an appropriate value if it is out of bounds, but newValue is a constant so it cannot be written to.  Perhaps something to fix in later versions of Swift?  Maybe, but for now, if you have to bound check, use a computed property that bound-checks, and then writes to the actual property you are trying to set.</p>
<h2>Property Observers are not called during Initialization</h2>
<p>This was mentioned in my previous post, but I will mention it again here.  In Swift, the property observers are NOT called during initialization or when a default value is set.  I&#8217;m not sure if it sets the backing variable directly, or if there is a flag set that suppresses the property observers (the iBook seems to suggest the former), but either way, they are not called when variables are written to from an initializer or with a default value.</p>
<p>There is one caveat to this, if you have a class that subclasses another, and sets its SUPERclass&#8217;s properties in an initializer, the SUPERclass&#8217;s property observers will be called for those properties.  Nonetheless, when you set properties in your own class from that own class&#8217;s initializer, the property observers are not called.</p>
<p>Properties that are told to lazy load (with the <span style="color: #bb2ca2;">lazy</span> keyword) cannot have property observers.  I can think of a few reasons why this is probably the case.  Firstly, you will set them out of an initializer, and then what would oldValue be for the <span style="color: #bb2ca2;">didSet</span> when you set it for the first time?  The whole point of a lazy loaded property is to not set the variable up until its getter is called.  That would probably leave the oldValue as nil, which would wreak havoc for non-optionals.  Not to mention that the getter may not be called in the property observers, so, would the value even be written set since a lazy property doesn&#8217;t want to load until the getter tells it to?  The more I think about it, the crazier adding property observers to lazily loaded properties becomes.  Maybe a future version of Swift will get them in a way that makes sense, like just ignoring any sets done until the getter is called the first time, but for now, property observers on lazy-loaded properties make no sense, so don&#8217;t try it.</p>
<h2>Conclusion</h2>
<p>While property observers aren&#8217;t the biggest feature in Swift, they do have their place.  They can be quite useful for value change notifications.  They also can be used to keep related values in sync if you don&#8217;t want to use a computed property (such as if computing the related value each time it is requested was computationally expensive).</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-PropertyObservers">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-property-observers/">Swift Property Observers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Class Initializers</title>
		<link>https://www.codingexplorer.com/class-initializers/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 19 Sep 2014 16:41:57 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=559</guid>

					<description><![CDATA[<p>Writing Class Initializers So, I have mentioned a few times about initializers on this blog.  I want to talk today about writing and using initializers for classes, later we can talk a bit more about how they are different for value types like structs or enumerations. Initializers do exactly what is sounds like they do, [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/class-initializers/">Class Initializers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Writing Class Initializers</h2>
<p>So, I have mentioned a few times about initializers on this blog.  I want to talk today about writing and using initializers for classes, later we can talk a bit more about how they are different for value types like structs or enumerations.</p>
<p>Initializers do exactly what is sounds like they do, they initialize your instances and get them ready to use.  Specifically, before an object can be used, it must set all of its stored properties to valid values.  This can be handled in one of three ways:</p>
<ul>
<li>Give them default values in their property definition</li>
<li>Set them during the initializer</li>
<li>Declare them as optionals</li>
</ul>
<p><span id="more-559"></span><br />
Now, I would not actually recommend declaring them as optionals unless you really need Swift&#8217;s optional functionality.  In the case of declaring them as optionals, they do not need to be given an explicit default value, nor must they be set in the initializer to be considered valid.  Optionals have an implicit default value of nil (well, actually its their .None case since they are actually just enumerations).  If you wish to learn more about Swift optionals, check out my previous posts <a title="Swift Optionals – Declaration, Unwrapping, and Binding" href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals – Declaration, Unwrapping, and Binding</a> and <a title="Optional Chaining and Implicitly Unwrapped Optionals in Swift" href="http://www.codingexplorer.com/optional-chaining-implicitly-unwrapped-optionals-swift/">Optional Chaining and Implicitly Unwrapped Optionals in Swift</a>.</p>
<p>So, the two main ways to set up stored properties are via default values, or via setting them in the initializer, as shown below:</p>
<pre class="lang:swift decode:true">class SampleClass {
    var aStringWithDefaultValue = "Default Value!"
    var aStringSetInAnInitializer: String
    
    init() {
        aStringSetInAnInitializer = "From the initializer!"
    }
}</pre>
<p>Above is the simplest form of the initializer.  It takes no arguments, and then just sets the value internally to that string literal.</p>
<p>In general though, if you are giving it a default value that does not need to be provided, like this string literal, you really should set it as a default value and not in the initializer.  For one, it lets you use type inference (notice that we had to set the type for aStringSetInAnInitializer, but not for aStringWithDefaultValue).  Secondly, it is just a lot more readable.</p>
<p>Initializers are a lot like functions, and have basically the same syntax, except the use of the word &#8220;init&#8221; instead of func.  There are a few nuances to how parameters are handled that we will go over in a bit, but they are still very similar.</p>
<p>As mentioned in my previous post <a title="Classes In Swift — An Introduction" href="http://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a>, for classes there is a default initializer generated.  It is like our initializer above, that takes no parameters, but unlike ours, it does nothing.  Therefore, it is only available to your classes if they have nothing that needs to be initialized.  If all of the properties are provided default values, or there are no properties, then you can use the default initializer.  Otherwise, you will either have to override it (like we did above), or make your own other initializers that take parameters to set up your properties.</p>
<p>One extra thing to note about this, normally, when a value is set, there are some functions called &#8220;property observers&#8221; that basically are willSet and didSet for whatever variable is being written to.  When you set your properties you can set how their getters and setters work (like in my post <a title="Computed Properties in Swift" href="http://www.codingexplorer.com/computed-properties-in-swift/">Computed Properties in Swift</a>), but for normal properties.  You can read about them in my post <a href="http://www.codingexplorer.com/swift-property-observers/">Swift Property Observers</a>.  In the same place, you can also handle the willSet and didSet case (being called just before and just after setting respectively).  When you set a value in either of the above ways (default values or initializers) in its own class, these observers are not called.  Bear that in mind if you need to use property observers.  If you subclass a type, and set a SUPERclass&#8217;s properties in the SUBclass&#8217;s initializer, the SUPERclass&#8217;s property observers will be called in that case.  In all other cases though, setting a property in an initializer doesn&#8217;t call property observers.</p>
<p>So, how do you call one of these initializers?  If you REALLY want, you could call the init directly like SampleClass.init(), but that seems needlessly verbose.  So much so, that I&#8217;m writing in the prose section of this text, and not in a code block because it would be ugly to use initializers that way.  You just call the initializer with the classes name, followed by the empty parenthesis, or the parameters if it takes any:</p>
<pre class="lang:swift decode:true">let ourClass = SampleClass()</pre>
<p>It is a lot more complicated to say than to just show.  That really is how simple it is to call them.</p>
<h2>Initializer Parameters</h2>
<p>You specify parameters for initializers the exact same way as you do for functions.  There are a few differences in how they are handled, but the syntax is basically the same:  An external name, followed by an internal name, a colon, and the type for that parameter, separated by commas.  Again, easier to show than to write:</p>
<pre class="lang:swift decode:true">init(externalName internalName: String, secondParameterExt secondParameterInternal: String) {
    aStringSetInAnInitializer = internalName + " " + secondParameterInternal
}</pre>
<p>Please NEVER use names like that, it hurt a little bit typing it, but I thought showing explicitly what each part was was more important than my typographical comfort.  With these terrible names, you would call this initializer like this:</p>
<pre class="lang:swift decode:true">let someObject = SampleClass(externalName: "Hey", secondParameterExt: "Swift")</pre>
<p>Which would store &#8220;Hey Swift&#8221; in our aStringSetInAnInitializer variable.</p>
<p>If no external name is supplied, is to use the internal name as an external name.  Say we had two initializers with these prototypes:</p>
<pre class="lang:default decode:true">init(firstValue: Int, secondValue: Int)
init(firstMultiplier: Int, secondMultiplier: Int)</pre>
<p>Without external parameter names, how would you know the difference of which one was referred to if you called an init with 2 Ints as arguments?  More importantly, how would the compiler know?  Therefore it needs some way to differentiate between them, and it uses those internal names to do it, if you don&#8217;t provide external ones.</p>
<p>If you really want, you can force it to have no external parameter names.  We even saw an example of this in a previous article <a title="Swift Strings" href="http://www.codingexplorer.com/swift-strings/">Swift Strings</a>,where it was used for String initializers that take numbers.  You give it an external parameter name of an underscore &#8220;_&#8221; .  That tells the compiler to not have an external name.  By the way, just for fun, I tried that with our two initializers above, and I got the appropriate error &#8220;invalid redeclaration of &#8216;init&#8217; &#8220;.  So basically, it saw both of them with the same name (despite different internal names), and as such said that it was being redeclared.</p>
<p>There are much better uses for this.  Apple&#8217;s iBook shows creating a Celsius object with no external parameter name, so that you just create your Celsius object with your Celsius temperature.  Another example could be making a &#8220;Pet&#8221; object, taking its name as a parameter, like this:</p>
<pre class="lang:swift decode:true">class Pet {
    let name: String
    
    init(_ name: String) {
        self.name = name
    }
}

//Called like this
let aPet = Pet("Kitty")</pre>
<p>Using that underscore well can increase readability, or make it worse, it all depends on the context. In this case, there is probably enough context that &#8220;Kitty&#8221; is the pet&#8217;s name.  For our multiplier or value initializers, that may not be the case (if we used the underscore).</p>
<p>You might have also noticed something. I wrote a let property, but did not give it a default value directly, I set it in the initializer.  I had mentioned this in my previous post <a title="Classes In Swift — An Introduction" href="http://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a>, but it of course stands to reason that I should mention it here.  Your object needs to have all of its properties set by the time the initializer is done.  As such, you can give your constants new values all you want in the initializer, as long as all of them are all given valid values by the end of the initializer.</p>
<p>Once the constant property is set in an initializer (or anywhere else, for that matter), it cannot be changed again.  If you try to in an initializer, you receive the appropriate error message, &#8220;Immutable value &#8216;self.thatValueName&#8217; may only be initialized once.&#8221;</p>
<h2>Conclusion</h2>
<p>This is just the beginning of using initializers.  We have predominantly covered how they are used with classes in this post.  We will cover the differences for value types like structs or enumerations another day.  There is also another very important part about initializers, how they are used with inheritance.  This post has gotten quite long, so we will cover that another time as well.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-ClassInitializers">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/class-initializers/">Class Initializers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Using a Nested Type in Swift</title>
		<link>https://www.codingexplorer.com/using-nested-type-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 12 Sep 2014 13:00:59 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=542</guid>

					<description><![CDATA[<p>In my previous post Classes In Swift — An Introduction, I mentioned that I should probably use an enumeration to denote what the status of my Message was (whether it was sent, received, or read).  Now, I could write a full MessageStatus enumeration with its own file that could be imported into any project, and [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/using-nested-type-swift/">Using a Nested Type in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In my previous post <a title="Classes In Swift — An Introduction" href="http://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a>, I mentioned that I should probably use an enumeration to denote what the status of my Message was (whether it was sent, received, or read).  Now, I could write a full MessageStatus enumeration with its own file that could be imported into any project, and that would work.  But really, this status is only supposed to talk about my custom class here, about my &#8220;Message&#8221; class.  Why go through all of the hassle to make this some generic MessageStatus enumeration that could be used on messages completely unrelated to my Message class?</p>
<p>This is exactly where we would want to use a nested type!<br />
<span id="more-542"></span></p>
<h2>What is a nested type?</h2>
<p>Well, a nested type is exactly what it sounds like.  I know, kind of anticlimactic.  Nonetheless, they can be very useful for situations such as these.  This enumeration only really makes since in this context, so it might as well actually be a nested type in our Message class.</p>
<p>So, let&#8217;s write a simple enumeration to describe what stage our Message currently is:</p>
<pre class="lang:swift decode:true">enum Status {
    case Sent
    case Received
    case Read
}</pre>
<p>If you want to learn more about enumerations, take a look at my previous post <a title="Enumerations in Swift" href="http://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a>.</p>
<p>Anyway, that is simple enough, now, how do we actually nest our nested type in Swift?  All we do is put it into our Message class from before, that is, inside of its curly braces:</p>
<pre class="lang:swift decode:true">class Message {

    enum Status {
        case Sent
        case Received
        case Read
    }
    
    //Modified stuff we wrote last time...
}</pre>
<p>I&#8217;ll include the entire Message class at the end of this post.</p>
<h2>Dot-Syntax and Type Inference with Nested Types</h2>
<p>So, now inside our Message class, we can set our status variable to be of the nested type Status, and refer to it as Status.Sent.  If the type can be inferred, we can even refer to it in the shorter way of just .Sent.</p>
<p>If you are outside of the Message class, with something that imports the Message class, how can you refer to this enumeration?  You would just use dot notation to look inside, so our nested type&#8217;s full name would be Message.Status.Sent, which again if the type is known, you can just use .Sent.</p>
<p>Having these as nested types also help keep the enumerations short, particularly in their native context, so as to avoid something like the Objective-C enumeration UIImagePickerControllerCameraCaptureModePhoto.  When imported into Swift, it can get shorter if the type can be inferred so you can use dot-syntax to set it to .Photo or .Video.  With how the Objective-C classes are imported, currently the enumeration is a nested type named UIImagePickerControllerCameraCaptureMode, within the UIImagePickerController class, which seems a bit needlessly verbose.  That means its full name is UIImagePickerController.UIImagePickerControllerCameraCaptureMode.Photo (for one setting).</p>
<p>If it was done fully in Swift, they probably would rename the nested enumeration CameraCaptureMode, within UIImagePickerController, resulting in its full name being UIImagePickerController.CameraCaptureMode.Video.  Nonetheless, the way they did it still lets you set it to .Photo or .Video when the type is known, so that is helpful.</p>
<h2>Using our Nested Type</h2>
<p>Let&#8217;s modify our Message class to take advantage of this.  Let&#8217;s say that this message class has a suggestion of what color to use on an indicator saying what stage the message is in on the UI. Right place for this? Probably not, but it would be one possible use for this capability.  It would probably be better in something using our Message class in its UI, so it would actually refer to this enumeration as Message.Status from the external context.  We will need to change our status variable as well, as shown below:</p>
<pre class="lang:default decode:true">var status = Status.Sent    //Change this from the original String form

//Add This
func statusColor() -&gt; UIColor {
    switch status {
    case .Sent:
        return UIColor(red: 1, green: 0, blue: 0, alpha: 1)
    case .Received:
        return UIColor(red: 0, green: 0, blue: 1, alpha: 1)
    case .Read:
        return UIColor(red: 0, green: 1, blue: 1, alpha: 1)
    }
}</pre>
<p>So with that, we are storing our status in its own enumeration, and calling it from the class it is nested in.</p>
<p>One other note, there is no significant limit to the amount of nesting used in nested types.  If you want a class in a class in a class&#8230; etc and have it 8 levels deep you can do it.  If you have to call it from the top level though, you will have to still use dot-syntax to access each successive level of nesting.</p>
<h2>Full Code for Modified Message Class</h2>
<p>For reference, here is our newly modified Message class (we didn&#8217;t touch TextMessage or ImageMessage):</p>
<pre class="lang:swift decode:true">class Message {
    //New
    enum Status {
        case Sent
        case Received
        case Read
    }
    //
    
    let sender: String
    let recipient: String
    
    let timeStamp: Date
    
    var status = Status.Sent  //Modified
    
    init(sender: String, recipient: String) {
        self.sender = sender
        self.recipient = recipient
        
        timeStamp = Date()
    }
    
    func basicInfo()-&gt;String {
        return "Time: \(timeStamp.description), Sender:  \(sender), Recipient:  \(recipient)"
    }
    
    func printInfo() {
        print(basicInfo())
    }
    
    //New
    func statusColor() -&gt; UIColor {
        switch status {
        case .Sent:
            return UIColor(red: 1, green: 0, blue: 0, alpha: 1)
        case .Received:
            return UIColor(red: 0, green: 0, blue: 1, alpha: 1)
        case .Read:
            return UIColor(red: 0, green: 1, blue: 1, alpha: 1)
        }
    }
    //
}</pre>
<h2>Conclusion</h2>
<p>Today&#8217;s Swift topic was rather simple, but it can be quite useful.  It also helps encapsulate the code, leaving this Swift enumeration only inside our Message class, where it is actually needed.  Being able to access different levels of nesting via dot-syntax is also very helpful, and helps keep the names short and easily readable.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftNestedTypes">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/using-nested-type-swift/">Using a Nested Type in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Classes In Swift — An Introduction</title>
		<link>https://www.codingexplorer.com/classes-in-swift-an-introduction/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 10 Sep 2014 21:54:44 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=245</guid>

					<description><![CDATA[<p>Classes are a very important part of any Object Oriented language, and Swift is no exception.  When I explain classes to people, I usually think of one to describe a car.  That&#8217;s a bit cliché, and done in a WWDC video, so let&#8217;s do something different. Creating A Class in Swift Let&#8217;s say we are making [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Classes are a very important part of any Object Oriented language, and Swift is no exception.  When I explain classes to people, I usually think of one to describe a car.  That&#8217;s a bit cliché, and done in a WWDC video, so let&#8217;s do something different.</p>
<h2>Creating A Class in Swift</h2>
<p>Let&#8217;s say we are making a chat program in Swift.  It primarily sends messages in text format, but occasionally, it will also send images.  We will first create our more general Message class, which we will specialize into those different formats later:</p>
<pre class="lang:swift decode:true">class Message {
    //Message code goes here
}</pre>
<p><span id="more-245"></span><br />
Simple enough, so now, we need to set up some properties to describe this message.  Well, all messages in this app will have a sender and a recipient, so we can add those.  A timestamp would also be useful to have.  Once the message is sent, those won&#8217;t change, so let&#8217;s create them as constants.  We should probably also have a property denoting what status the message is (sent, received, or read), and that will change as time goes on, so that will be a variable.  You can read more about constants and variables in my previous post, <a title="Swift Variables and Constants" href="http://www.codingexplorer.com/swift-variables/">Swift Variables and Constants</a>.  You create properties by simply declaring variables at the class scope (outside of methods), like so:</p>
<pre class="lang:swift decode:true">class Message {
    let sender: String
    let recipient: String
    
    let timeStamp: Date
    
    var status = "Sent"
}</pre>
<p>One note, the status really should be an enumeration with the 3 states I mentioned above.  For simplicity&#8217;s sake, I am using a Swift String since we are not here to discuss enumerations in this post.  If you are curious, you can see my previous post <a title="Enumerations in Swift" href="http://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a>.</p>
<p>Now, if you type this into your Swift Playground directly, you will get the nice error &#8220;Class &#8216;message&#8217; has no initializers&#8221;, and since we did not type one that is correct!  Well, technically Swift can generate a blank initializer for classes.  The default blank initializer does nothing about the stored properties though.  All properties must have a valid value when a class is initialized, and since we did not give all of these default values, the blank initializer is insufficient.  You could write your own and give default values inside it if you wanted though, but the auto-generated one won&#8217;t work.</p>
<p>Anyway, we should probably write an initializer shouldn&#8217;t we?  In this program, I&#8217;m thinking that these message objects will be created when the user sends the message.  At that point, the content of the message is ready, and we create the object with that content, and set the aforementioned properties.  If you want to learn more about initializers, check out the post <a href="http://www.codingexplorer.com/class-initializers/">Class Initializers</a>.  For this class, we&#8217;ll write the simple one below:</p>
<pre class="lang:swift decode:true">init(sender: String, recipient: String) {
    self.sender = sender
    self.recipient = recipient

    timeStamp = Date()
}</pre>
<p>We gave the status a default value in the class definition, so it was not mentioned here (since I said a Message object was created when it is being sent, we gave it a default value of such).  It took parameters denoting the sender and recipient, and stored those to the internal versions.  You may notice that I named the inputs to the initializer the same as the name of the properties in this class.  Obviously I cannot just say sender=sender, so I use the keyword <span style="color: #bb2ca2;">self</span>, and then use dot-syntax to access that property of <span style="color: #bb2ca2;">self</span>, to refer to the fact that I want the internal &#8220;sender&#8221; to be set to the property of the instance of this class&#8217;s &#8220;sender&#8221; property.  I then set timeStamp to the current time/date with Date&#8217;s default initializer.  I could use <span style="color: #bb2ca2;">self</span>.timeStamp if I wanted, but since I had no competing variable name, it was unnecessary.</p>
<h2>Inheriting From Classes</h2>
<p>Now, I said that these messages could take text of images as the actual content of the message.  We currently have a message that contains the sender, recipient, time stamp, and status, but no content.  We&#8217;ll make two more classes TextMessage and ImageMessage, and inherit those other capabilities from our message base class:</p>
<pre class="lang:swift decode:true">class TextMessage: Message {
    let content: String
    
    init(content: String, sender: String, recipient: String) {
        self.content = content
        super.init(sender: sender, recipient: recipient)
    }
}

class ImageMessage: Message {
    let content: UIImage
    
    init(content: UIImage, sender: String, recipient: String) {
        self.content = content
        super.init(sender: sender, recipient: recipient)
    }
}</pre>
<p>So, TextMessage and ImageMessage now subclass the Message class, getting all of the previous functionality we needed.  They also add what they need, in this case their content being a Swift String or UIImage respectively.  Maybe using Generics here would be a better choice, but this is not to make a full fledged chat program, but to show how classes work.</p>
<p>So, when we initialize your TextMessage, that initializer takes the 2 values we needed previously (sender and recipient), but also a value for content.  We set that content to the (self.content) to what was sent in as a parameter.  We then call our superclass&#8217;s initializer (the one we wrote earlier), and initialize it with the sender and recipient the TextMessage initializer received as a parameter.</p>
<p>You may notice, in these initializers, I am setting the value of a constant (a <span style="color: #bb2ca2;">let</span> property).  That may look unusual since in general, you assign to <span style="color: #bb2ca2;">let</span> values when they are declared and nowhere else.  A <span style="color: #bb2ca2;">let</span> variable must be assigned to exactly once.  It must be given a value when our class is created, since it is property of the class, which means the only other place (if not given a default value), is in the initializer.  <del>You can even assign to it multiple times in the initializer if you REALLY want, but it must be set to something by the end of the initializer.  This is in contrast to normal use of a constant in other situations, where once it is given a value, then it cannot be written to again.  I am not sure exactly how this difference is achieved.  I would guess that it waits to actually assign it to a permanent place in memory until the initializer is complete.  Nonetheless, that is one special aspect of Swift initializers.</del></p>
<p><strong>Update June 16, 2015:</strong> Since Swift 1.2 (or Xcode 6.3 beta 1), this is no longer the case.  A constant in an initializer can ONLY be written to once.  Previously, it could be written multiple times as long as it had a valid value by the end of the initializer.  I&#8217;m not sure why someone would want to do that, but nonetheless, at this point it is no longer possible.  The compiler will give you an error if you attempt to write to it multiple times stating that &#8220;Immutable value &#8216;propertyName&#8217; may only be initialized once.&#8221;</p>
<h2>Functions and Methods are not the same thing?</h2>
<p>Now, there is a finer point about syntax that I have glossed over for a while.  I have used the words function and method a lot in this blog but not fully defined them.  I did talk about functions in my previous post <a title="Functions in Swift: Parameters and Return Types" href="http://www.codingexplorer.com/functions-swift-parameters-return-types/">Functions in Swift: Parameters and Return Types</a>, but what exactly are methods?</p>
<p>The answer is actually rather simple, methods are functions of a type (in Swift, this includes classes, structures, or enumerations).  All methods are functions, but not all functions are methods.</p>
<p>It also sounds a bit cliché, but it is true.  For instance, in Swift, you can write a function within the scope of another function.  If we wrote one inside of a method (a function directly associated with a type), would it make sense to call that a nested method?  I cannot call it from the type&#8217;s context, only from that method of the type, so it isn&#8217;t directly associated with the type its enclosing method is.  Also, in the playground, you can write functions at top level code, outside of classes, and since they are not tied to a class, they also cannot be called methods.</p>
<h2>Inheriting and Overriding Methods</h2>
<p>Another note about inheritance in Swift, it doesn&#8217;t work for just properties, it works for methods too.  Subclasses can inherit, or even override methods.  Subclasses can also override properties as well, but let&#8217;s just talk about methods for now.  Let&#8217;s add these methods to our Message class:</p>
<pre class="lang:swift decode:true">func basicInfo()-&gt;String {
    return "Time: \(timeStamp.description), Sender:  \(sender), Recipient:  \(recipient)"
}

func printInfo() {
    print(basicInfo())
}</pre>
<p>Without any extra work, these are already inherited by our subclasses, so we can instantiate a class, and call either of these directly from our subclass:</p>
<pre class="lang:default decode:true ">let someMessage = TextMessage(content: "Hello World!", sender: "Your App", recipient: "The World")

someMessage.printInfo()</pre>
<p>Now, let&#8217;s say we want to specialize the printInfo method, and have it show the content for our TextMessage class along with that additional information, we would have to override the old behavior and write a new one, which we do with the override keyword like so (in our TextMessage class):</p>
<pre class="lang:swift decode:true">override func printInfo() {
    print("\(basicInfo()), Content:  \(content)")
}</pre>
<p>You must use the override keyword when overriding something from a superclass.  It helps make your code safer by first, making sure you accidentally don&#8217;t override something you didn&#8217;t even know existed (like if you wanted some custom description method, but did not know description was already a valid function in your superclass).  It also tells the compiler to verify that you actually ARE overriding something, I would guess to check for typos (like like trying to override &#8220;description&#8221;, but you actually wrote &#8220;descirption&#8221; (I inverted the r and the i in the middle).</p>
<p>Now when we call printInfo, it will call our subclass&#8217;s version of the method, which calls the superclass&#8217;s basicInfo for the first part of the Swift String, and appended the new information to the end.  We could call <span style="color: #bb2ca2;">super</span>.basicInfo(), but since we didn&#8217;t override it, there was no need to specify which one, since there is only one.</p>
<h2>Obligatory discussion about Classes being Reference Types</h2>
<p>I have touched on this in a few different posts, but now that we are officially talking about classes, I should mention it again here.</p>
<p><span style="text-decoration: underline;"><strong>Classes are reference types.</strong></span></p>
<p>That means a few things.  Firstly, if we assign our someMessage variable to another variable, then we are pointing to the same instance of the class.  Unlike structs (such as the Swift Array) or enumerations, the values are not copied to the new variable.  That means that if you change something in the otherMessage variable that we assigned someMessage to, we change someMessage as well.</p>
<p>Secondly, it means that I can, somewhat, mutate our constants, because the constant aspect is not the class instance itself.  This was touched on in <a title="Swift Variables and Constants" href="http://www.codingexplorer.com/swift-variables/">Swift Variables and Constants</a>, but basically, when you assign your class to a variable, the object is created and put in memory, and your variable or constant stores a reference to that object.  You cannot assign your constant stored value to point to another instance of that class.  You can however, modify the values inside the object that is referenced.</p>
<p>This will be a bit clearer with a few examples, as shown below:</p>
<pre class="lang:default decode:true">let someMessage = TextMessage(content: "Hi!", sender: "Me", recipient: "You")

print(someMessage.status)
//Output:  "Sent"

let otherMessage = someMessage
otherMessage.status = "Received"

print(someMessage.status)
//Output:  "Received"

//Changing otherMessage changed what someMessage pointed to.
someMessage = TextMessage(content: "Won't Work", sender: "Compiler", recipient: "You")
//error: cannot assign to value: 'someMessage' is a 'let' constant</pre>
<p>Just for reference, here is the entire code for our sample classes, so you can see everything in context:</p>
<pre class="lang:swift decode:true ">class Message {
    let sender: String
    let recipient: String
    
    let timeStamp: Date
    
    var status = "Sent"
    
    init(sender: String, recipient: String) {
        self.sender = sender
        self.recipient = recipient
        
        timeStamp = Date()
    }
    
    func basicInfo()-&gt;String {
        return "Time: \(timeStamp.description), Sender:  \(sender), Recipient:  \(recipient)"
    }
    
    func printInfo() {
        print(basicInfo())
    }
}

class TextMessage: Message {
    let content: String
    
    init(content: String, sender: String, recipient: String) {
        self.content = content
        super.init(sender: sender, recipient: recipient)
    }
    
    override func printInfo() {
        print("\(basicInfo()), Content:  \(content)")
    }
}

class ImageMessage: Message {
    let content: UIImage
    
    init(content: UIImage, sender: String, recipient: String) {
        self.content = content
        super.init(sender: sender, recipient: recipient)
    }
}</pre>
<h2>Conclusion</h2>
<p>Classes are all over programs in Swift and Objective-C.  Some of this may be review, especially at this point, but I thought it would be useful to work through a few concepts via a non-trivial example to show how classes are written and how inheritance works.  Stay tuned for some other aspects about how classes work, particularly about initializers.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftClassesIntro">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swift Dictionary Quick Reference</title>
		<link>https://www.codingexplorer.com/swift-dictionary-quick-reference/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 09 Sep 2014 05:47:21 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=508</guid>

					<description><![CDATA[<p>The Swift dictionary is another very useful type of collection in Swift.  Like arrays (which you can read more about in my post Arrays and their Methods in Swift), you access them via subscripts usually.  Unlike Swift arrays though, these subscripts accept many more values besides Ints.  There are some limitations, but it nonetheless gives [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-dictionary-quick-reference/">Swift Dictionary Quick Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The Swift dictionary is another very useful type of collection in Swift.  Like arrays (which you can read more about in my post <a title="Arrays and their Methods in Swift" href="http://www.codingexplorer.com/arrays-swift/">Arrays and their Methods in Swift</a>), you access them via subscripts usually.  Unlike Swift arrays though, these subscripts accept many more values besides Ints.  There are some limitations, but it nonetheless gives you a lot more capability than arrays if you need they key used to look it up to be something other than a number.  We will also go over some of the methods for dictionaries as well, but there are not nearly as many as for arrays.<br />
<span id="more-508"></span></p>
<h2>Swift Dictionary Command Quick Reference</h2>
<p>Here is a table that lists and explains major methods and related syntax for Swift dictionaries.  Some of these are pretty self explanatory (like count or isEmpty), and were already gone over in the array post.  If you see some of these not covered and you want to know more, you can take a look at my previous post <a title="Arrays and their Methods in Swift" href="http://www.codingexplorer.com/arrays-swift/">Arrays and their Methods in Swift</a>.  We will go over the others a bit more in depth afterwards.</p>
<table border="1">
<tbody>
<tr>
<td style="padding: 5px;">Title</td>
<td style="padding: 5px;">Example</td>
<td style="padding: 5px;">Description</td>
</tr>
<tr>
<td style="padding: 5px;">Dictionary Shorthand Type</td>
<td style="padding: 5px;">[<span style="color: #703daa;">String </span>: <span style="color: #703daa;">Double</span>]</td>
<td style="padding: 5px;">This is used when explicitly declaring the type of the dictionary.  This example is a type for a dictionary that has Strings for keys, and Doubles for values.</td>
</tr>
<tr>
<td style="padding: 5px;">Dictionary Literal</td>
<td style="padding: 5px;">[<span style="color: #d12f1b;">&#8220;Regular&#8221;</span> : <span style="color: #272ad8;">3.85</span>, <span style="color: #d12f1b;">&#8220;Premium&#8221;</span> : <span style="color: #272ad8;">4.15</span>, <span style="color: #d12f1b;">&#8220;Diesel&#8221;</span> : <span style="color: #272ad8;">4.09</span>]</td>
<td style="padding: 5px;">This is a shorthand way to generate a dictionary of known objects.  The keys and values must be the same type respectively, but the key and value type do not have to be the same.</td>
</tr>
<tr>
<td style="padding: 5px;">Initialize Empty Dictionary</td>
<td style="padding: 5px;">[<span style="color: #703daa;">String </span>: <span style="color: #703daa;">Double</span>]()</td>
<td style="padding: 5px;">This initializes an empty Dictionary that has Strings for keys, and Doubles for values.</td>
</tr>
<tr>
<td style="padding: 5px;">Empty Dictionary Literal</td>
<td style="padding: 5px;">[:]</td>
<td style="padding: 5px;">This initializes an empty dictionary.  The dictionary must have its type explicitly (initializing) or previously stated (emptying existing dictionary).</td>
</tr>
<tr>
<td style="padding: 5px;">Subscript Syntax</td>
<td style="padding: 5px;">gasPrices[<span style="color: #d12f1b;">&#8220;Regular&#8221;</span>]</td>
<td style="padding: 5px;">The standard way to retrieve a value from a dictionary.  This example retrieves the value with the String key of &#8220;Regular&#8221;.  Returns an optional of the value type, containing nil if the value is not present.</td>
</tr>
<tr>
<td style="padding: 5px;">Number of Elements</td>
<td style="padding: 5px;">gasPrices.<span style="color: #703daa;">count</span></td>
<td style="padding: 5px;">This returns an Int of how many values are in the dictionary.</td>
</tr>
<tr>
<td style="padding: 5px;">isEmpty Shorthand</td>
<td style="padding: 5px;">gasPrices.<span style="color: #703daa;">isEmpty</span></td>
<td style="padding: 5px;">This returns a Bool describing whether the dictionary is empty or not.  If count is 0, this returns true, otherwise it will return false.</td>
</tr>
<tr>
<td style="padding: 5px;">Update Value For Key</td>
<td style="padding: 5px;">gasPrices.<span style="color: #3d1d81;">updateValue</span>(<span style="color: #272ad8;">4.00</span>, forKey: <span style="color: #d12f1b;">&#8220;Regular&#8221;</span>)</td>
<td style="padding: 5px;">This updates the value for the key &#8220;Regular.&#8221;  It then returns the previous value that it is supplanting, which is nil if there was no value for that key.</td>
</tr>
<tr>
<td style="padding: 5px;">Remove Value For Key</td>
<td style="padding: 5px;">gasPrices.<span style="color: #3d1d81;">removeValue</span>(f<span style="color: #3d1d81;">orKey: </span><span style="color: #d12f1b;">&#8220;Diesel&#8221;</span>)</td>
<td style="padding: 5px;">This will remove the value for the key &#8220;Diesel.&#8221;  Like Update Value For Key, it will return the previous value it is removing, which is nil if the value did not exist in the first place.</td>
</tr>
<tr>
<td style="padding: 5px;">Remove All Values</td>
<td style="padding: 5px;">gasPrices.<span style="color: #703daa;">removeAll</span>()</td>
<td style="padding: 5px;">Removes all values from dictionary.  Can take a Bool for keepCapacity to not change capacity value.  If omitted, defaults to false and sets capacity to 0.</td>
</tr>
<tr>
<td style="padding: 5px;">Iterate Over Dictionary</td>
<td style="padding: 5px;"><span style="color: #bb2ca2;">for</span> (gasType, gasPrice) <span style="color: #bb2ca2;">in</span> gasPrices</td>
<td style="padding: 5px;">This iterates over the dictionary, and assigns the keys to the first variable in the tuple, and the value to the second variable in the tuple.</td>
</tr>
<tr>
<td style="padding: 5px;">Get Collection of Keys</td>
<td style="padding: 5px;">gasPrices.<span style="color: #703daa;">keys</span></td>
<td style="padding: 5px;">This returns a collection that can be iterated through of the keys of this dictionary. It is not an array.</td>
</tr>
<tr>
<td style="padding: 5px;">Get Collection of Values</td>
<td style="padding: 5px;">gasPrices.<span style="color: #703daa;">values</span></td>
<td style="padding: 5px;">This returns a collection that can be iterated through of the values of this dictionary. It is not an array.</td>
</tr>
</tbody>
</table>
<p>There are a few more, but I highly doubt you will be wanting the internal index that a dictionary uses.  It might be useful for a quick lookup, but other than that, since the order of values is not guaranteed, it seems like a comparatively unhelpful couple of methods.</p>
<h2>Creating a Swift Dictionary</h2>
<p>Like Swift arrays, you can create your dictionaries using either initializers or literals, as demonstrated below:</p>
<pre class="lang:swift decode:true">var literalDictionary = ["Breakfast" : "Cereal", "Lunch" : "Sandwich", "Dinner" : "Pizza"]
var emptyDictionary = [String : String]()</pre>
<p>We first used a literal to create a dictionary that had Strings for keys and Strings for values.  We then used an initializer to create an empty dictionary of the same type.  Afterwards, I cleared that dictionary again, using an empty dictionary literal.  The dictionary literal and type syntax is of the style [Key: Value].  For the type syntax used in the initializer, you just place the type of the key on the left, and the type of the value on the right.  For the literal, each element of the dictionary is written that way, with the key object on the left of the colon, and the value object on the right side of the colon.  If you want additional values, you just separate each of these groupings with a comma, like we did in the example above about different meals.  For the literal, you can have different types for the keys and values, but all of the keys must be of the same type, and all of the values must be of the same type.</p>
<p>Much like the array, the above used type syntax is actually just a better looking form of the dictionary&#8217;s actual type, which is <span style="color: #703daa;">Dictionary</span>&lt;<span style="color: #703daa;">String</span>, <span style="color: #703daa;">String</span>&gt;.  You can use this if you want, but the square-bracketed form is significantly more readable than this one, so it is preferred.  Internally, a Swift dictionary is (like the array), a struct, meaning that it is a value type, and assigning it to a new variable copies it, and does <strong>NOT</strong> point to the same instance of a dictionary.</p>
<p>You can see the empty dictionary literal in action in my previous post <a title="Custom Subscripts in Swift" href="http://www.codingexplorer.com/custom-subscripts-swift/">Custom Subscripts in Swift</a>.  I felt that it was about time to cover it more officially.</p>
<h2>Updating Dictionary Values</h2>
<p>You would normally update a value by simple setting to it via subscript notation.  You would remove a key from the dictionary by updating it to a value of nil.  Both of these styles are shown below:</p>
<pre class="lang:swift decode:true">literalDictionary["Dinner"] = "Salad"
literalDictionary["Breakfast"] = nil  //Never do this, breakfast is the most important meal of the day!</pre>
<p>Swift also provides you with an additional set of methods to do the same thing, but with a twist.  You could also use these methods:</p>
<pre class="lang:swift decode:true">let replacedValue = literalDictionary.updateValue("Salad", forKey: "Dinner")
let removedValue = literalDictionary.removeValue(forKey: "Breakfast")</pre>
<p>What these two methods do, is return an optional of the value that was just updated.  This lets you compare what you set to what was there, to see if anything actually was changed.  You could <span style="color: #3d1d81;">updateValue</span> to nil to remove the value, but it just seems a bit easier to just use a method that does that automatically for whatever key you give it.</p>
<h2>Dictionary Keys must be Hashable</h2>
<p>You can use any type as a value for a Swift dictionary. However, for the fast lookup, all keys must be hashable. The built in Swift types like Int, Double, and String are hashable, and usually the best way to make a custom class hashable, is to change it into one of those and hash it. I found a very good example of how to do this in Swift at Kirby Shabaga&#8217;s blog <a title="How to implement Hashable for your custom class — Swift Coder" href="http://www.swiftcoder.info/dev/codefellows/2014/8/2/how-to-implement-hashable-for-your-custom-class">How to implement Hashable for your custom class — Swift Coder</a>. It shows you how to adopt the <span style="color: #703daa;">Hashable</span> protocol and still works as of the current version of Xcode mentioned in the conclusion of this page. In that post, the custom class is a customized CGPoint. The gist of making it hashable, is implementing the <span style="color: #703daa;">Hashable</span> protocol, and then making a string of the X and Y coordinates, getting the hashValue of that String, and returning that as the hashValue of the custom type.</p>
<h2>Conclusion</h2>
<p>While there are not nearly as many methods for the Swift dictionary type, I thought it would be useful to have them in a quick, easy to reference table.  This of course is also available in Apple&#8217;s iBook, but in a much longer format.  Again, I only covered newer concepts in this post, and many of the ones I covered are extremely analogous to their counterparts for arrays, so you can find more information about most of the ones I did not cover in my post <a title="Arrays and their Methods in Swift" href="http://www.codingexplorer.com/arrays-swift/">Arrays and their Methods in Swift</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftDictionary">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="How to implement Hashable for your custom class — Swift Coder" href="http://www.swiftcoder.info/dev/codefellows/2014/8/2/how-to-implement-hashable-for-your-custom-class">How to implement Hashable for your custom class — Swift Coder</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-dictionary-quick-reference/">Swift Dictionary Quick Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Closures and Capturing Values in Swift</title>
		<link>https://www.codingexplorer.com/closures-capturing-values-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 03 Sep 2014 09:59:15 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=502</guid>

					<description><![CDATA[<p>We aren&#8217;t done with closures quite yet.  We learned last time about how to write and compress closure expressions in the post Closure Expressions in Swift.  Now, how about we talk about making functions that take them as parameters or return them!  I am still very new to closures, so I do not fully know [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/closures-capturing-values-swift/">Closures and Capturing Values in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>We aren&#8217;t done with closures quite yet.  We learned last time about how to write and compress closure expressions in the post <a title="Closure Expressions in Swift" href="http://www.codingexplorer.com/closure-expressions-swift/">Closure Expressions in Swift</a>.  Now, how about we talk about making functions that take them as parameters or return them!  I am still very new to closures, so I do not fully know the power that these hold, so my examples will only show the tip of the iceberg.  When I understand more, I will definitely come back and share, but for the moment, I have to know how to get started with them, so let&#8217;s see how that goes.<br />
<span id="more-502"></span></p>
<h2>Closure Type</h2>
<p>So, when you want to take a parameter to a function, or return a value, you normally have to specify a type.  So, how do you specify a the &#8220;type&#8221; of a closure when doing so?  This may look somewhat similar to my post <a title="Functions in Swift: Parameters and Return Types" href="http://www.codingexplorer.com/functions-swift-parameters-return-types/">Functions in Swift: Parameters and Return Types</a>, but as we said, functions are a type of closure.</p>
<p>Firstly, the simplest type of a closure is this:</p>
<pre class="lang:swift decode:true">()-&gt;()</pre>
<p>It is a closure that takes no parameters, and returns nothing, so if we wanted to take this as a parameter we would use it like so:</p>
<pre class="lang:default decode:true">func functionToRunAClosure(someClosure: () -&gt; ()) -&gt; String {
    someClosure()
    
    return "I ran the closure!"
}

functionToRunAClosure(someClosure: {print("I'm printing something!")})</pre>
<p>Here we wrote a function that runs a closure given to it, and then we handed that function a closure expression that just printed something to the console.  After running the closure, we just returned a string saying that we ran the closure.  In this case I ignored the return, but I just wanted to show what the syntax for a function that takes a closure but has a more standard type of return.</p>
<p>If we wanted to return a closure that takes no arguments and returns nothing itself, we would do something like this:</p>
<pre class="lang:swift decode:true">func makeClosureToPrintExclamationString(someString: String) -&gt; ()-&gt;() {
    let result = { print("\(someString)!!") }
    
    return result
}

let yellAboutAwesomeSwiftSite = makeClosureToPrintExclamationString(someString: "Coding Explorer is awesome")

yellAboutAwesomeSwiftSite()
//Output: "Coding Explorer is awesome!!"</pre>
<p>The syntax does look a bit odd at the end with the &#8221; -&gt; ()-&gt;() &#8220;.  It is just saying that it returns a closure that takes no arguments and returns nothing.  Remember that in Swift, a function that returns nothing really returns an empty tuple?  More precisely, it returns a closure that has an empty tuple&#8217;s-worth of arguments, and returns an empty tuple.</p>
<p>So, how do you make your closures actually take arguments or return values themselves?  Just think of those tuples like you think of a normal function prototype in Swift.  The leftmost parenthesis holds the types of your parameters, and the rightmost parenthesis holds the return type (or types if it returns a full-fledged tuple).  If the return type is just a single type (not a tuple itself), you don&#8217;t have to surround it with parenthesis.</p>
<pre class="lang:swift decode:true">func makeClosureThatReturnsStringAboutAwesomeGroup() -&gt; ()-&gt;String {
    let result = { () -&gt; String in return "SwiftLDN is Awesome!" }
    return result
}</pre>
<p>In this case, the function returns a closure that returns a Swift String, and the closure is created by a closure expression that just returns a Swift String.  This function is hard-coded to return the same Swift String each time.  However, what if I wanted to make a function that takes a String, and returns a closure that talks about how awesome that String is?  In that case, we would have to take a String and somehow keep a reference to it after the function that makes the closure goes out of scope.  How is that done?</p>
<h2>Capturing Values in Closures</h2>
<p>In Swift, you do that by capturing values when you make your closure, of course!  Okay, that isn&#8217;t really obvious, but that&#8217;s what I&#8217;m here to help with.  So, let us make the awesomeMaker function, that returns a closure that talks about how awesome some String you pass into awesomeMaker is.  It would look something like this:</p>
<pre class="lang:swift decode:true">func awesomeMaker(subject: String) -&gt; ()-&gt;String {
    let result = { () -&gt; String in return "\(subject) is Awesome!" }
    return result
}

let codingInSwiftStatement = awesomeMaker(subject: "CodingInSwift")

print(codingInSwiftStatement())
//Output: "CodingInSwift is Awesome!"</pre>
<p>Now, we can state that anything is awesome by just passing its name to awesomeMaker.  Whenever we want to state it, we just insert the call to the closure we made about CodingInSwift, in this case.</p>
<p>If we use awesomeMaker again with another string, it has no effect on the first one we made.  It will capture a new value that we send it, and each awesomeMaker-made closure says what it was supposed to, like this:</p>
<pre class="lang:swift decode:true">let soSoSwiftStatement = awesomeMaker(subject: "SoSoSwift")

print(codingInSwiftStatement())
//Output: "CodingInSwift is Awesome!"
print(soSoSwiftStatement())
//Output: "SoSoSwift is Awesome!"</pre>
<h2>But Closures are Actually Reference Types?</h2>
<p>There is one somewhat confusing thing about this.  While each closure created by awesomeMaker is independent, if we created another variable and assigned codingInSwiftStatement to it, they are actually pointing to the same closure.  In this case, that doesn&#8217;t change much since nothing changes between calls to the closure, but what if we had a closure that would yell a String louder each time, like this:</p>
<pre class="lang:swift decode:true">func yellSomethingLouder(subject: String) -&gt; ()-&gt;String {
    var exclamationPoints = 0
    
    let result = { () -&gt; String in
        exclamationPoints += 1
        
        let workingString = subject + String(repeating: "!", count: exclamationPoints)
        
        return workingString
    }
    return result
}</pre>
<p>See what happens when we use this, and assign it to a new variable below:</p>
<pre class="lang:swift decode:true">let yellComputer = yellSomethingLouder(subject: "Computer")

print(yellComputer())  //Output: "Computer!"
print(yellComputer())  //Output: "Computer!!"
print(yellComputer())  //Output: "Computer!!!"


let yellAtOtherComputer = yellComputer

print(yellAtOtherComputer())  //Output: "Computer!!!!"
</pre>
<p>When we just set yellAtOtherComputer to the value of yellComputer, it kept counting up on those exclamation points!  Much like classes, in Swift, closures are actually reference types.  We just told the compiler to set what yellAtOtherComputer to point to wherever yellComputer is pointing.  If it was a value type, it would be copied and would be a separate instance, but instead they are pointing to the same instance.</p>
<p>I was a bit curious at what happened if I create a new closure with the exact same literal, let&#8217;s see what happens:</p>
<pre class="lang:swift decode:true">let yellAtThirdComputer = yellSomethingLouder(subject: "Computer")

print(yellAtThirdComputer())  //Output: "Computer!"

print(yellComputer())         //Output: "Computer!!!!!"</pre>
<p>I actually wasn&#8217;t entirely sure what would happen before I tried this.  This seemed most likely, but there was a chance it would optimize and just tie it to the same closure since they were made via the exact same means.  This does make sense though.  In our case, that optimization might seem like a good idea, but what if we wanted to append the date this closure was created for some reason?  Then it wouldn&#8217;t make sense to tie them to the same closure.  Since the compiler doesn&#8217;t know if I&#8217;m doing something simple (like the above), or like that date idea, it has to assume you are making a new closure, since you called yellSomethingLouder again to make a new closure.</p>
<p>In case you thought yellAtOtherComputer did in fact copy, and just keep counting from 4 exclamation points, you can see that when we ran yellComputer again, it had 5 exclamation points.  If yellAtOtherComputer had copied, then yellComputer would not have been incremented yet, and would only have 4 exclamation points above.</p>
<h2>Conclusion</h2>
<p>This post used closure expressions very often to simplify writing closures for the examples.  If you missed my previous post about them, you might want to go back to <a title="Closure Expressions in Swift" href="http://www.codingexplorer.com/closure-expressions-swift/">Closure Expressions in Swift</a>, for a better explanation on how to use them and their syntax.  I am just beginning to understand how useful closures can be, as evidenced by how silly these examples were.  These examples try to show the syntax with as little fluff about other concepts as I could, but that did mean we had closures that just called print, when one would normally just call print themselves.</p>
<p>I will definitely come back as I learn more about closures in Swift and share more about what they can do, but I do think awesomeMaker and yellSomethingLouder are beginning to show what they are capable of.  They help encapsulate functionality in a (potentially) terser way, so someone can call a closure made by awesomeMaker instead of calling a more general use function each time, supplying the same parameter each time.  In other words, one can call iPhoneIsAwesome (made by awesomeMaker) instead of saySomethingIsAwesome(&#8220;iPhone&#8221;) each time.  Then if you want to change the subject, you just change it on the awesomeMaker line, instead of on each function call to saySomethingIsAwesome.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftClosures">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/closures-capturing-values-swift/">Closures and Capturing Values in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Closure Expressions in Swift</title>
		<link>https://www.codingexplorer.com/closure-expressions-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 30 Aug 2014 03:42:16 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=489</guid>

					<description><![CDATA[<p>Closures are a very useful part of Swift.  An Int is a type that stores an Integer, a String is a type that holds a string.  In the same way, a closure is, basically, a type that holds a function.  With this capability, you can do many things with closures that you couldn&#8217;t do in [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/closure-expressions-swift/">Closure Expressions in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Closures are a very useful part of Swift.  An Int is a type that stores an Integer, a String is a type that holds a string.  In the same way, a closure is, basically, a type that holds a function.  With this capability, you can do many things with closures that you couldn&#8217;t do in several older languages.  You can assign closures to a variable, you can pass them as arguments to other functions, you can even return one from a function.</p>
<p>Closures in Swift are similar to blocks in Objective-C.  In fact, when you call an Objective-C API from Swift that wants a block, you pass in a closure.  The major difference between them is coding style, and that closure expressions are much easier to read and write in Swift.<br />
<span id="more-489"></span></p>
<h2>Functions are Closures?</h2>
<p>You may not have realized it, but we have already been using closures in Swift.  Functions in Swift are actually a certain type of closure.  I&#8217;ll let Apple&#8217;s iBook speak for itself here:</p>
<blockquote><p>Closures take one of three forms:</p>
<ul>
<li>Global functions are closures that have a name and do not capture any values.</li>
<li>Nested functions are closures that have a name and can capture values from their enclosing function.</li>
<li>Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.</li>
</ul>
<p>Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l</p></blockquote>
<p>Today, we are going to discuss a bit about the third, particularly how to remove a lot of the fluff and compress them down into a very readable, but concise form.</p>
<p>Remember the array&#8217;s <span style="color: #3d1d81;">map</span> method that was mentioned in my previous post <a title="Arrays and their Methods in Swift" href="http://www.codingexplorer.com/arrays-swift/">Arrays and their Methods in Swift</a>?  The <span style="color: #3d1d81;">map</span> method takes a closure as an argument, performs that closure on every element of the array, and returns back a new array of what is returned.  This new array doesn&#8217;t even have to be of the same type. Let us say we wanted to greet everybody on an array called guestList.  We could generate strings for greeting them like so:</p>
<pre class="lang:swift decode:true">func greetPeople(person: String) -&gt; String {
    return "Hello, \(person)!"
}


let guestList = ["Chris", "Jill", "Tim"]
let fullGreetings = guestList.map(greetPeople)</pre>
<p>We made a greetPeople function, and then passed that into the <span style="color: #3d1d81;">map</span> method for our guestList array.  It then went through, generated the full greeted Strings, and then returned them to us, where we stored them in fullGreetings.</p>
<p>&nbsp;</p>
<h2>Closure Expression Compression</h2>
<p>This could be made more succinct using some of the shortcuts available to us from Swift.  If we only really need to do this greeting once, we don&#8217;t really need a function for it.  Naming the function lets us call it anywhere, and we simply don&#8217;t need that capability, we only want to call this once, and we can cache those returned strings for later, if need be.</p>
<p>This is where we can use closure expressions.  I particularly like <a title="A Basic Tutorial on Functions and Closures in Swift | Airspeed Velocity" href="http://airspeedvelocity.net/2014/06/11/a-basic-tutorial-on-functions-and-closures-in-swift/">Airspeedvelocity&#8217;s</a> explanation of Closure Expressions.  Closure expressions, are basically function &#8220;literals.&#8221;  The more official title for them are anonymous functions.  When you just need a quick function stated in only one place (like in a completion handler), you don&#8217;t need to give it a name, and just pass in the code for the function directly.  Some other programming languages refer to them as Lambda expressions.</p>
<p>Here is the most complete and explicit form of our code above used as a closure expression:</p>
<pre class="lang:swift decode:true">let fullGreetings = guestList.map({(person: String) -&gt; String in return "Hello, \(person)!"})</pre>
<p>It might look a little messy, but it is still better than having that whole separate function written out when you would only use it once anyway.  In its fullest form, the syntax for a closure expression is a normal function prototype (minus the <span style="color: #bb2ca2;">func</span> keyword), followed by <span style="color: #bb2ca2;">in</span>, and then the actual body of the closure expression.  The <span style="color: #bb2ca2;">in</span> basically tells it that the prototype is complete, and the rest is what the closure expression actually does.</p>
<p>Below I am going to quickly step through the various ways to make this Swift closure expression even more succinct.</p>
<p>First of all, this is Swift!  We have type inference now, let us get rid of those types from the parameters:</p>
<pre class="lang:swift decode:true">let fullGreetings = guestList.map({(person) -&gt; String in return "Hello, \(person)!" })</pre>
<p>Actually, the compiler can see that we are returning a string (since we do say &#8216;return &#8220;Some String&#8221; &#8216;in the closure), so we don&#8217;t even need the return type in there either, so let&#8217;s take that out:</p>
<pre class="lang:swift decode:true">let fullGreetings = guestList.map({person in return "Hello, \(person)!"})</pre>
<p>For single expression closures, like ours, the only expression in the closure body is a string literal we are creating, so we don&#8217;t even need the &#8220;return&#8221; keyword there either, so we&#8217;ll get rid of that next:</p>
<pre class="lang:swift decode:true">let fullGreetings = guestList.map({person in "Hello, \(person)!" })</pre>
<p>Actually, Swift has shorthand names for the parameters to the closure expression in the form of $0, $1, $2, and so on.  With that, we don&#8217;t even need to state the names of the parameters, or the <span style="color: #bb2ca2;">in</span> keyword either:</p>
<pre class="lang:swift decode:true">let fullGreetings = guestList.map({ "Hello, \($0)!" })</pre>
<p>While not as useful here, since this is all on one line, in larger closure expressions, we can make this a bit more readable with trailing closure syntax.  It lets you put the curly braces on the outside, to look more like a normal function:</p>
<pre class="lang:swift decode:true">let fullGreetings = guestList.map(){ "Hello, \($0)!" }</pre>
<p>Finally, since we don&#8217;t have anything else in the parenthesis for the <span style="color: #3d1d81;">map</span> method, we can actually just remove them altogether:</p>
<pre class="lang:swift decode:true">let fullGreetings = guestList.map{ "Hello, \($0)!" }</pre>
<p>Now that is a compact closure expression, and makes what it does very obvious.</p>
<h2>Conclusion</h2>
<p>This is only the beginning of our discussions about closures and closure expressions.  There is more to come, especially about writing your own functions that take closures.  Check out my next post <a href="http://www.codingexplorer.com/closures-capturing-values-swift/">Closures and Capturing Values in Swift</a> to learn how to do that.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftClosureExpressionCompress">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="A Basic Tutorial on Functions and Closures in Swift | Airspeed Velocity" href="http://airspeedvelocity.net/2014/06/11/a-basic-tutorial-on-functions-and-closures-in-swift/">A Basic Tutorial on Functions and Closures in Swift by Airspeedvelocity</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/closure-expressions-swift/">Closure Expressions in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Custom Subscripts in Swift</title>
		<link>https://www.codingexplorer.com/custom-subscripts-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 25 Aug 2014 09:26:37 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=461</guid>

					<description><![CDATA[<p>Last time we talked about Arrays in Swift, and the main way to acquire a value was to look it up via an index using subscripts.  Swift made it rather easy to implement subscripts in your own classes.  Sure you can use an Array or Dictionary type if you wanted, and in many cases you [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/custom-subscripts-swift/">Custom Subscripts in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Last time we talked about <a title="Arrays and their Methods in Swift" href="http://www.codingexplorer.com/arrays-swift/">Arrays in Swift</a>, and the main way to acquire a value was to look it up via an index using subscripts.  Swift made it rather easy to implement subscripts in your own classes.  Sure you can use an Array or Dictionary type if you wanted, and in many cases you should, but if writing it in subscript syntax is clearer and more expressive, that is a good reason to use it.<br />
<span id="more-461"></span></p>
<h2>Getting and Setting via Subscripts</h2>
<p>Lets say we have this class below:</p>
<pre class="lang:swift decode:true">class DailyMeal {
    enum MealTime {
        case Breakfast
        case Lunch
        case Dinner
    }
    
    var meals: [MealTime : String] = [:]
}</pre>
<p>As it is, we would use this by querying the <span style="color: #4f8187;">meals</span> dictionary directly, like so:</p>
<pre class="lang:swift decode:true">let monday = DailyMeal()

monday.meals[.Breakfast] = "Toast"

if let someMeal = monday.meals[.Breakfast] {
    print(someMeal)
}</pre>
<p>Now, we already made this <span style="color: #4f8187;">monday</span> of the <span style="color: #4f8187;">DailyMeal</span> type, so we already know meals should be stored here, so wouldn&#8217;t it be easier to just ask <span style="color: #4f8187;">monday</span> about <span style="color: #31595d;">.Breakfast</span>?  We would add this right after our <span style="color: #4f8187;">meals</span> variable in the <span style="color: #4f8187;">DailyMeal</span> class:</p>
<pre class="lang:swift decode:true">subscript(requestedMeal: MealTime) -&gt; String? {
    get {
        return meals[requestedMeal]
    }
    set(newMealName) {
        meals[requestedMeal] = newMealName
    }
}</pre>
<p>This looks a lot like a Swift computed property.  You can read more about computed properties in my post <a title="Computed Properties in Swift" href="http://www.codingexplorer.com/computed-properties-in-swift/">Computed Properties in Swift</a>.  The major difference is the function prototype at the top.  It uses the <span style="color: #bb2ca2;">subscript</span> keyword first, then it takes a parameter and describes a return type.  The parameter is what goes in the subscript (between the square brackets).  In an Array, that&#8217;s the Int that describes the index.  In Dictionaries, that is whatever is used as the key.</p>
<p>Then, like computed properties, we write the getter and setter method. In both of these cases, we are still calling the meals dictionary, but we are covering up the details from the user.</p>
<p>We can now use the class like so:</p>
<pre class="lang:swift decode:true">var monday = DailyMeal()

monday[.Breakfast] = "Toast"

if let someMeal = monday[.Breakfast] {
    print(someMeal)
}</pre>
<p>In this example, it would then print &#8220;Toast&#8221; to the console.</p>
<p>Much better on the setting, but all of that optional binding still makes this messy, lets rewrite that subscript a little bit and remove that implementation detail:</p>
<pre class="lang:swift decode:true">subscript(requestedMeal: MealTime) -&gt; String {
    get {
        if let thisMeal = meals[requestedMeal] {
            return thisMeal
        } else {
            return "Ramen"
        }
    }

    set(newMealName) {
        meals[requestedMeal] = newMealName
    }
}</pre>
<p>We&#8217;re still actually <strong>doing</strong> the optional binding, but we moved it inside the subscript to make things easier on the user.  Now this subscript always returns a Swift String.  If they have not set a meal name for that <span style="color: #4f8187;">mealTime</span> (the dictionary returns nil), then we just assume they&#8217;re having Ramen.  Ramen is always a great default meal.</p>
<p>Now we can just call it like so:</p>
<pre class="lang:swift decode:true">let monday = DailyMeal()

monday[.Lunch] = "Pizza"

print(monday[.Lunch])         //Output:  "Pizza"

print(monday[.Dinner])        //Output:  "Ramen"</pre>
<p>Now that is some clean code.  This hides your implementation details from the class using <span style="color: #4f8187;">DailyMeal</span>.  If you need to change your API underneath, as long as it still ties the internal representation to that subscript, anything calling your API won&#8217;t need to change.  For reference, the entire <span style="color: #4f8187;">DailyMeal</span> class now looks like:</p>
<pre class="lang:swift decode:true">class DailyMeal {
    enum MealTime {
        case Breakfast
        case Lunch
        case Dinner
    }

    var meals: [MealTime : String] = [:]

    subscript(requestedMeal: MealTime) -&gt; String {
        get {
            if let thisMeal = meals[requestedMeal] {
                return thisMeal
            } else {
                return "Ramen"
            }
        }

        set(newMealName) {
            meals[requestedMeal] = newMealName
        }
    }
}</pre>
<h2>Read-Only Subscripts</h2>
<p>Read-Write subscripts are usually used as fronts for internal Arrays or Dictionaries.  Read-only subscripts can be, but I have seen some instances of using them in other ways in Swift, like mathematical calculations.  In Apple&#8217;s Swift iBook, you can see an example of using them for a custom times table, where you set the multiplier and call a subscript for an entry in that multiplier&#8217;s times-table column, and returns that value.</p>
<p>In an effort to show other examples to give you multiple perspectives on these features, I have made a simple factorial generator.  You don&#8217;t even need to set an extra variable, just create the class and ask it for a factorial.</p>
<pre class="lang:swift decode:true">struct FactorialGenerator {
    subscript(n: Int) -&gt; Int {
        var result = 1

        if n &gt; 0 {
            for value in 1...n {
                result *= value
            }
        }

        return result
    }
}</pre>
<p>It is a little longer, but that is mostly because factorials are a bit more complex than multiplication alone.</p>
<p>You may notice that I don&#8217;t have <span style="color: #bb2ca2;">get</span> or <span style="color: #bb2ca2;">set</span> written in this subscript.  If you only want it to be read-only, then you can omit the <span style="color: #bb2ca2;">get</span> keyword.  The Swift compiler will just treat what you have written as a getter.  If another class attempts to set via this subscript, a compiler error will be thrown.</p>
<p>So now with this factorial generator, you can just call it like this:</p>
<pre class="lang:swift decode:true ">let factorial = FactorialGenerator()

print("Five factorial is equal to \(factorial[5]).")
//Output:  "Five factorial is equal to 120."

print("Ten Factorial is equal to \(factorial[10]).")
//Output:  "Ten Factorial is equal to 3628800."</pre>
<p>Now that is a concise way to request a factorial that isn&#8217;t actually an array underneath.  This way is a bit computational heavy, so if you request factorials a lot, you might want to make this an array underneath that is created upon initialization, or maybe generated on another thread so it doesn&#8217;t block the UI.  Either way though, using subscripts lets you hide those details from the user of the <span style="color: #4f8187;">FactorialGenerator</span> class.  If you start doing it this way, and change your mind in later versions of your API, then the user won&#8217;t have to change their code, as long as <span style="color: #4f8187;">FactorialGenerator</span> still ties the internal representation of the values to these subscripts.</p>
<p>Another good example of using read-only subscripts was pointed out to me by Natasha The Robot.  It is a nicer way of handling JSON in Swift named <a title="lingoer/SwiftyJSON" href="https://github.com/lingoer/SwiftyJSON">SwiftyJSON</a>, written by Ruoyu Fu, available on <a title="lingoer/SwiftyJSON" href="https://github.com/lingoer/SwiftyJSON">GitHub</a>.  You should also check out Natasha&#8217;s website <a title="Natasha The Robot" href="http://natashatherobot.com/">natashatherobot.com</a> for other great articles about Swift.</p>
<h2>Conclusion</h2>
<p>Subscripting is a very powerful part of Swift.  To paraphrase John McCall from WWDC Session 404 &#8220;Advanced Swift,&#8221; and to quote Stan Lee:  &#8220;With great power, comes great responsibility.&#8221;  Apparently that phrase goes all the way back to Voltaire, but I digress.</p>
<p>Since Swift subscripts are basically glorified computed properties, you can do anything a normal Swift function can do.  You can make calls to other functions, you could draw on screen, you could even call to a hardware device if you wanted, but you probably shouldn&#8217;t (unless doing so REALLY IS required to get information in that subscript (like if that index was telling you the status of an IO pin on Raspberry Pi or something like that).</p>
<p>When you use subscripts, be careful that you treat them like a subscript.  Ideally you should be calling into something where your subscript is essentially an index, and then getting or setting it like you were using an Array or Dictionary.</p>
<p>We have been entrusted with a powerful language feature in Swift.  We must all strive to use it wisely and clearly.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftSubscripts">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/custom-subscripts-swift/">Custom Subscripts in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Arrays and their Methods in Swift</title>
		<link>https://www.codingexplorer.com/arrays-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 20 Aug 2014 05:20:45 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=443</guid>

					<description><![CDATA[<p>Arrays are a very common component in many programming languages.  Swift is no different.  Arrays are an ordered list of objects of the same type in Swift.  This is the case for arrays in most other programming languages, but Objective-C&#8217;s NSArray was capable of holding values of different types in the same NSArray.  In that case, they were [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/arrays-swift/">Arrays and their Methods in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Arrays are a very common component in many programming languages.  Swift is no different.  Arrays are an ordered list of objects of the same type in Swift.  This is the case for arrays in most other programming languages, but Objective-C&#8217;s <span style="color: #703daa;">NSArray</span> was capable of holding values of different types in the same <span style="color: #703daa;">NSArray</span>.  In that case, they were stored as <span style="color: #bb2ca2;">id</span>, and thus took a bit more work to change them back into whatever type they actually were.  Swift simplifies it by enforcing that all values are of the same type.  This in particular makes things safer, so you don&#8217;t have to check what type a variable is when you take it out of a Swift array.<br />
<span id="more-443"></span></p>
<h2>Swift Array Command Quick Reference</h2>
<p>Below I have included a simple table that will show the major functions and operators for Arrays, and we will go a bit more in depth with them afterwards:</p>
<table border="1">
<tbody>
<tr>
<td style="padding: 5px;"><strong>Title</strong></td>
<td style="padding: 5px;"><strong>Example</strong></td>
<td style="padding: 5px;"><strong>Description</strong></td>
</tr>
<tr>
<td style="padding: 5px;">Array Shorthand Type</td>
<td style="padding: 5px;">[<span style="color: #703daa;">Int</span>]</td>
<td style="padding: 5px;">This is used when explicitly declaring the type of the array.  This example is a type for an array of Ints.</td>
</tr>
<tr>
<td style="padding: 5px;">Array Literals</td>
<td style="padding: 5px;">[1, 3, 7, 12, 40]</td>
<td style="padding: 5px;">This is a shorthand way to generate an array of known objects.  They must all be of the same type.</td>
</tr>
<tr>
<td style="padding: 5px;">Initialize Empty Array</td>
<td style="padding: 5px;">[<span style="color: #703daa;">Int</span>]()</td>
<td style="padding: 5px;">This initializes an empty array of type Int.</td>
</tr>
<tr>
<td style="padding: 5px;">Initialize With Repeating Value</td>
<td style="padding: 5px;">[<span style="color: #703daa;">Int</span>](repeating: 40, count: 7)</td>
<td style="padding: 5px;">This initializes an integer array with 7 elements, each at a value of 40.</td>
</tr>
<tr>
<td style="padding: 5px;">Subscript Syntax</td>
<td style="padding: 5px;">someArray[0]</td>
<td style="padding: 5px;">The standard way to retrieve a value from an array.  This example retrieves the 1st object (at index 0)</td>
</tr>
<tr>
<td style="padding: 5px;">First Element Shorthand</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">first</span></td>
<td style="padding: 5px;">This returns an optional containing the first value in the array, or nil if the array is empty.</td>
</tr>
<tr>
<td style="padding: 5px;">Last Element Shorthand</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">last</span></td>
<td style="padding: 5px;">This returns an optional containing the last value in the array, or nil if the array is empty.</td>
</tr>
<tr>
<td style="padding: 5px;">Number of Elements</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">count</span></td>
<td style="padding: 5px;">This returns an Int of how many values are in the array.</td>
</tr>
<tr>
<td style="padding: 5px;">isEmpty Shorthand</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">isEmpty</span></td>
<td style="padding: 5px;">This returns a Bool describing whether the array is empty or not.  If count is 0, this returns true, otherwise it will return false.</td>
</tr>
<tr>
<td style="padding: 5px;">Append to Array</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">append</span>(5)</td>
<td style="padding: 5px;">This appends a new element containing the Int 5 to our Int array.</td>
</tr>
<tr>
<td style="padding: 5px;">Append Shorthands</td>
<td style="padding: 5px;">someArray+=[5]</td>
<td style="padding: 5px;">Shorthand for above.  The value must stored in an array itself, even if it contains only 1 element like this example.</td>
</tr>
<tr>
<td style="padding: 5px;">Insert Value at Index</td>
<td style="padding: 5px;">someArray.<span style="color: #3d1d81;">insert</span>(42, at: 3)</td>
<td style="padding: 5px;">This will insert a value of 42 into the array at index 3.</td>
</tr>
<tr>
<td style="padding: 5px;">Remove Value at Index</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">remove</span>(at: 2)</td>
<td style="padding: 5px;">This will remove the value at index 2.  It will return that value, but it can be ignored if you only wanted to remove it.</td>
</tr>
<tr>
<td style="padding: 5px;">Remove at End of Array</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">removeLast</span>()</td>
<td style="padding: 5px;">Same as above for the last element in the array.  Makes checking array upper bound unnecessary for final value.</td>
</tr>
<tr>
<td style="padding: 5px;">Remove All Values</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">removeAll</span>()</td>
<td style="padding: 5px;">Removes all values from array.  Can take a Bool for keepCapacity to not change capacity value.  If omitted, defaults to false and sets capacity to 0.</td>
</tr>
<tr>
<td style="padding: 5px;">Add Array</td>
<td style="padding: 5px;">someArray + anotherArray</td>
<td style="padding: 5px;">This returns a new array that contains the elements of someArray first, followed by the elements of anotherArray afterwards.</td>
</tr>
<tr>
<td style="padding: 5px;">Reverse Array</td>
<td style="padding: 5px;">someArray.<span style="color: #703daa;">reversed</span>()</td>
<td style="padding: 5px;">This returns an array that has all elements in the reverse order from source array.</td>
</tr>
</tbody>
</table>
<p>There are several more, but these are some of the most important.  I&#8217;m not sure I would use the reverse method very often, but I&#8217;m glad it&#8217;s there.</p>
<h2>Creating Arrays</h2>
<p>Like other built in types to Swift, there are two major ways to create arrays, with a literal or an initializer.  An example of how to create Int arrays with each are shown below:</p>
<pre class="lang:swift decode:true">let literalArray = [0,1,1,2,3,5,8,13,21]
var emptyArray = [Int]()
let defaultValueArray = [Int](repeating: 0, count: 5)</pre>
<p>The third one is also an initializer, but it lets you create an array with a certain number of elements with an initial value set.  In this case, it creates the equivalent of the literal [0,0,0,0,0], an array of 5 Integers, all set to 0.</p>
<p>The [<span style="color: #703daa;">Int</span>] is actually shorthand for the full form of an Array of type Int:  <span style="color: #703daa;">Array</span>&lt;<span style="color: #703daa;">Int</span>&gt;.  This was not listed in the quick reference, because while it is how it is created under the hood, Apple encourages using the shorthand due to its increased readability.</p>
<p>Does something look a bit familiar with that type?  It is using generics!  Generic types are similar to generic functions, but they are types that are generalized to take in different types of values.  They are most often used with collection types, including arrays of course, but also Dictionaries.  The example in Apple&#8217;s iBook uses a stack, another type of collection, to show how they work and are created.  If you want to learn more, check out my post on <a title="Generic Types in Swift" href="http://www.codingexplorer.com/generic-types-swift/">Generic Types in Swift</a>.  You can also learn a bit more about Generics from an earlier post <a title="Generic Functions in Swift" href="http://www.codingexplorer.com/generic-functions-in-swift/">Generic Functions in Swift</a>.</p>
<p>One thing to note, arrays act a little differently depending on how they are stored.  An array stored as a <span style="color: #bb2ca2;">var</span> is completely mutable.  You can change it, append or remove objects however you want.  An array stored as a <span style="color: #bb2ca2;">let</span> constant is completely immutable.  You can read from it, but you cannot change anything.</p>
<h2>Accessing Array Values</h2>
<p>There are several ways to read values from your array in Swift.  The first, and most standard way, is via subscript syntax:</p>
<pre class="lang:swift decode:true">let fourthValueOfArray = literalArray[3]</pre>
<p>As the variable name says, this reads the fourth value of literalArray.  In C, and most other languages, arrays count up from 0, so that is why the fourth value is at index 3.  This may be made more obvious by a small chart:</p>
<table border="1">
<tbody>
<tr>
<td style="padding: 5px;">index</td>
<td style="padding: 5px;">0</td>
<td style="padding: 5px;">1</td>
<td style="padding: 5px;">2</td>
<td style="padding: 5px;"><strong>3</strong></td>
<td style="padding: 5px;">4</td>
<td style="padding: 5px;">5</td>
<td style="padding: 5px;">6</td>
<td style="padding: 5px;">7</td>
<td style="padding: 5px;">8</td>
</tr>
<tr>
<td style="padding: 5px;">literalArray Value</td>
<td style="padding: 5px;">0</td>
<td style="padding: 5px;">1</td>
<td style="padding: 5px;">1</td>
<td style="padding: 5px;"><strong>2</strong></td>
<td style="padding: 5px;">3</td>
<td style="padding: 5px;">5</td>
<td style="padding: 5px;">8</td>
<td style="padding: 5px;">13</td>
<td style="padding: 5px;">21</td>
</tr>
</tbody>
</table>
<p>You can see that the fourth element is index 3, and contains the number 2.</p>
<p>There are also a few shortcuts to read certain elements of an Array in Swift.  To read the first and last values of an array in most languages you would have to manually set it to an array bound.  That is easy for the first one, that&#8217;s just [0], but the last one, that usually required something like [literalArray.<span style="color: #703daa;">count</span> &#8211; 1] in many other languages.  Yeah, it works, but it is not very succinct.  Apple decided to add some nice shortcuts to these that made it a lot more obvious what you&#8217;re doing, and just make the code look cleaner.  They added the first and last computed properties:</p>
<pre class="lang:swift decode:true">let firstValue = literalArray.first  //Returns Optional Int containing 0
let lastValue = literalArray.last    //Returns Optional Int containing 21</pre>
<p>These return optional values of the type of the array that contain the first and last values of the array respectively.  Why an optional?  Well, what is the first or last value of the emptyArray we made earlier?  If the array is empty, this returns a nil, otherwise, it will return an optional containing first or last value.  Even if the array only has 1 element, it will still return an optional containing the first and last value, which happen to be the same index in that case.  You will have to optionally bind, or otherwise somehow unwrap the value to get back the initial Int, like you have to with most optionals.  You can learn more about optionals from my post <a title="Swift Optionals – Declaration, Unwrapping, and Binding" href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals – Declaration, Unwrapping, and Binding</a>.</p>
<p>One other way to get values from an array, if you want to go through all of them, is with a for-loop.  You can use a normal for loop and set the ranges manually, or you can use the for-in loop.</p>
<pre class="lang:swift decode:true">var sum = 0

for number in literalArray {
    sum += number
}</pre>
<p>This small snippet adds each of the numbers together from our literal array by iterating over them an just adding them to the value of sum.  You can read more about the for-in loop from my post <a title="Loops, Switch Statements, and Ranges in Swift" href="http://www.codingexplorer.com/loops-switch-statements-ranges-swift/">Loops, Switch Statements, and Ranges in Swift</a>.</p>
<p>When I learned about the foreach loop in C# (the equivalent of the Swift for-in loop), I started using it everywhere, but then I would sometimes run into an issue.  I would want to step through something but would sometimes need the index.  Swift has given that capability here with the magic of tuples and the <span style="color: #3d1d81;">enumerate</span> method.</p>
<pre class="lang:swift decode:true">for (index, number) in literalArray.enumerated() {
    print("Fibonacci Number \(index):  \(number)")
}
//Last Line Output:  "Fibonacci Number 8:  21"</pre>
<p>That prints out 9 lines describing the numbers listed in literalArray, which were the Fibonacci numbers.  I didn&#8217;t want to clutter this further with all 9 lines, but I included the last one above.  The <span style="color: #3d1d81;">enumerate</span> in that for-in loop is a global function that returns a tuple composed of the index and value of what it is enumerating through.  If you want to learn more about Tuples, check out my post <a title="Tuples in Swift: Create, Read, and Return" href="http://www.codingexplorer.com/tuples-in-swift-create-read-and-return/">Tuples in Swift: Create, Read, and Return</a>.</p>
<h2>Number of Elements in an Array</h2>
<p>There are a couple ways to check how many elements are in the array.  The simple one is the count command.  It will return an Int containing how many values are in the array:</p>
<pre class="lang:swift decode:true">let elementsInArray = literalArray.count  //returns 9</pre>
<p>That&#8217;s simple enough.  Now, if you want to check if you have any values, sure you could compare if the count is greater than 0, or you could just ask the array if it is empty:</p>
<pre class="lang:swift decode:true">let emptyStatus = literalArray.isEmpty  //returns false</pre>
<p>That just returns a boolean describing whether the array is empty.  If the count is above 0, it returns true, otherwise it returns false.</p>
<h2>Mutating an Array</h2>
<p>For mutable arrays (arrays created as a <span style="color: #bb2ca2;">var</span>), you have several different ways to mutate arrays</p>
<h3>Adding to the Array</h3>
<p>You can append to the end of an array, or insert a value at a certain index.  To append, you can use the <span style="color: #703daa;">append</span> command, or the shorthand += operator, as shown below:</p>
<pre class="lang:swift decode:true">emptyArray.append(5)
emptyArray += [5]</pre>
<p>Those two statements are functionally equivalent for this task.  One thing to note, to use the += operator, you must actually have an array on the righthand side, even if it is only of one value.  The extra part about that though, is that if you want to add more than one value, you just add to that array literal, so you could add more values to the array like this:</p>
<pre class="lang:swift decode:true">emptyArray += [9, 8, 7, 6]</pre>
<p>Now the (now inappropriately named) emptyArray contains [5, 5, 9, 8, 7, 6] (since we added two 5s to it earlier).</p>
<p>You can insert a value at an arbitrary place as well with the insert command, like this:</p>
<pre class="lang:swift decode:true">emptyArray.insert(12, at: 2)
//emptyArray now is [5, 5, 12, 9, 8, 7, 6]</pre>
<p>We inserted the value 12 at index 2.  This shifted the former index of 2, and everything above it up by one, and put the value we wanted at index 2.</p>
<h3>Removing from the Array</h3>
<p>You can also remove from the array as well.  We can remove from a specific index if we want:</p>
<pre class="lang:swift decode:true">let valueThatWasRemoved = emptyArray.remove(at: 3)
//emptyArray now is [5, 5, 12, 8, 7, 6]</pre>
<p>We removed that 9 that was at index 3 with the <span style="color: #703daa;">remove(at:</span> command.  It also has the added ability to return the value that was removed, which we stored in valueThatWasRemoved.  This can be ignored and not stored if you just wanted to remove the value.  This is obviously the inverse of the <span style="color: #3d1d81;">insert</span>:atIndex: command.</p>
<p>The inverse of the <span style="color: #703daa;">append</span> command is the <span style="color: #703daa;">removeLast</span> command, as shown below:</p>
<pre class="lang:swift decode:true">let formerlyLastValue = emptyArray.removeLast()
//emptyArray now is [5, 5, 12, 8, 7]</pre>
<p>Like the <span style="color: #703daa;">removeAtIndex</span> command, this also returns its value, which we stored in the formerlyLastValue variable.</p>
<p>Wasn&#8217;t this emptyArray supposed to be an empty array?  Lets just get rid of all of this:</p>
<pre class="lang:swift decode:true">emptyArray.removeAll()
//emptyArray now is empty once more</pre>
<p>This method actually takes an argument on whether you want to keep the capacity or not as it was (so it won&#8217;t need to reallocate memory if you plan on refilling it soon).  If omitted (like above), it defaults to false, and sets the capacity back to zero.  If you did want to keep the capacity, you would use the method like this:</p>
<pre class="lang:swift decode:true">let originalCapacity = emptyArray.capacity   //originalCapacity = 6
emptyArray.removeAll(keepCapacity: true)
let newCapacity = emptyArray.capacity        //newCapacity = 6</pre>
<p>This was for emptyArray when it had the values [5, 5, 12, 8, 7], so it could apparently store 6 values before reallocation.  For removeAll() with no parameters, the newCapacity would equal 0.</p>
<h2>Create new Arrays based on Previous ones</h2>
<p>You can combine two arrays by simply using the + operator.  It returns a new array that puts the elements on the left-hand side first, and the elements on the right-hand side afterwards.</p>
<pre class="lang:swift decode:true">var arrayOne = [1, 2, 3, 4, 5]
var arrayTwo = [30, 40, 50]

var bothArrays = arrayOne + arrayTwo
//bothArrays now is 1, 2, 3, 4, 5, 30, 40, 50]</pre>
<p>If you really want, you can even have the reverse-ordered form of the array returned as a new array as well with the aptly named <span style="color: #703daa;">reverse</span> command:</p>
<pre class="lang:swift decode:true ">let normalArray = [20, 21, 22, 23, 24, 25]
let reversedArray = normalArray.reversed()
//reversedArray now is [25, 24, 23, 22, 21, 20]</pre>
<p>I&#8217;m not sure when I&#8217;d use it, but it&#8217;s still good that it&#8217;s there.  The reason why reversedArray was explicitly typed as an array is that if not, the type inference actually creates it as a ReversedCollection&lt;[Int]&gt; type, which also is a CollectionType like Array, that apparently handles the reverse itself.  When reversedArray is explicitly typed, it lets you see its result again as an Array.</p>
<h2>Conclusion</h2>
<p>We&#8217;ve covered many methods that can be performed on arrays.  There is one particularly important one, named <span style="color: #3d1d81;">map</span>, but we will cover that one another time.  The <span style="color: #3d1d81;">map</span> method performs a block of code to each element of an array, which is called a closure.  You can check out my post about <a href="http://www.codingexplorer.com/closure-expressions-swift/">Closure Expressions in Swift</a>., to learn more about the <span style="color: #3d1d81;">map</span> method and other information about Closures.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftArrays">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/arrays-swift/">Arrays and their Methods in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swift Strings</title>
		<link>https://www.codingexplorer.com/swift-strings/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 15 Aug 2014 12:08:07 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=363</guid>

					<description><![CDATA[<p>Strings are a very common type of variable in many programming languages.  Strings are sequences of characters, used to store text.  Swift in particular works with them in a Unicode-compliant way.  In this post we will discuss some of the higher level aspects of working with Strings in Swift.  The Swift String is very different [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-strings/">Swift Strings</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Strings are a very common type of variable in many programming languages.  Strings are sequences of characters, used to store text.  Swift in particular works with them in a Unicode-compliant way.  In this post we will discuss some of the higher level aspects of working with Strings in Swift.  The Swift String is very different from its predecessor NSString, but they are bridged together in such a way that you can use a Swift string anywhere you would use an NSString.  You can also use NSString methods on Swift Strings.  In Swift 1.2, NSStrings are not automatically bridged to Swift Strings (but they were beforehand), they must be typecast using the &#8220;as&#8221; operator.  Swift Strings can still be used where an NSString is expected though, so you only have to typecast an NSString to its Swift equivalent if you still have one.</p>
<p><span id="more-363"></span></p>
<h2>String Literals</h2>
<p>Firstly, I never really learned what &#8220;literal&#8221; in this context meant directly.  I eventually figured it out from context, but I felt I should just say it outright for others like me that keep hearing it, but don&#8217;t actually get told the definition.  I feel Wikipedia&#8217;s introductory line about <a title="Literal (computer programming) - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Literal_(computer_programming)">Literals</a> does it justice:  &#8220;In computer science, a literal is a notation for representing a fixed value in source code.&#8221;</p>
<p>In Swift, as in most languages, a String literal is just text written between two quotation marks.  You can bind it to a variable or constant, as well as use it directly as a parameter to a function.</p>
<p>There are also a few special characters that can be used in String literals to describe special things like tabs or new lines.  These include:</p>
<ul>
<li>\0 &#8211; Null character (that is a zero after the slash)</li>
<li>\\ &#8211; Backslash itself.  Since the backslash is used to escape other characters, it needs a special escape to actually print itself.</li>
<li>\t  &#8211; Horizontal tab</li>
<li>\n &#8211; Line Feed</li>
<li>\r  &#8211; Carriage Return</li>
<li>\&#8221;  &#8211; Double quote.  Since the quotes denote a String literal, this is necessary if you actually want to print one.</li>
<li>\&#8217;  &#8211; Single Quote.  Similar reason to above.</li>
</ul>
<p>Sadly, it appears <a title="character encoding - What is a vertical tab? - Stack Overflow" href="http://stackoverflow.com/a/3380554/2775523">vertical tab</a> did not make the cut.</p>
<h2>String Initializers</h2>
<p>Besides using string literals, Swift provides another way to create strings, initializers.  They are overloads of the String init method that take different arguments and create a Swift String version of that variable.</p>
<h3>Empty Strings</h3>
<p>Swift gives two easy ways to create an empty string.  The first is to just use an empty string literal, the second is to initialize a string with no parameters, like so:</p>
<pre class="lang:swift decode:true">let someString = String()</pre>
<p>Since there are no parameters, the initializer has no choice but to return an empty string, ready and waiting to have additional information concatenated to it.</p>
<h2>Swift Strings are Structures</h2>
<p>Strings in Swift are not implemented via a class, they are actually structures.  That means they are value types.  That in turn means that when you assign them to a new variable, they are copied, so when you change the original String that was copied, the newly stored one is unaffected.  This is in contrast to NSString in Objective-C, which was a class, and would be passed by reference.  If you changed one reference to that initial NSString, you changed them both.</p>
<h2>Working with Strings</h2>
<p>Strings have a few operators that make working with them easier.</p>
<h3>String Concatenation</h3>
<p>Like in other languages, Strings can be concatenated (put together) with a plus sign &#8221; + &#8221; operator.  It just basically has the compiler create a string with the characters of the second string placed at the end of the first string.  For example:</p>
<pre class="lang:swift decode:true">let firstString = "I like "
let secondString = "Swift!"

let wholeSentence = firstString + secondString
print(wholeSentence)</pre>
<p>That will print the sentence &#8220;I like Swift!&#8221; to the console.</p>
<h3>String Comparison</h3>
<p>As one would expect, you can compare if two strings are the same like you would in any other equality test, with &#8221; == &#8221; and &#8221; != &#8220;.  These will return a Bool describing whether they are equal or not.  Since Swift Strings are Unicode based, and I know very little about Unicode, I will let Apple&#8217;s iBook define String equality for me:</p>
<blockquote><p>“Two String values (or two Character values) are considered equal if their extended grapheme clusters are canonically equivalent. Extended grapheme clusters are canonically equivalent if they have the same linguistic meaning and appearance, even if they are composed from different Unicode scalars behind the scenes.”</p>
<p>Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l</p></blockquote>
<p>If you wanted to store whether two strings were equal to each other to a variable, you would do it like so:</p>
<pre class="lang:swift decode:true">let firstSentence  = "This is a sentence."
let secondSentence = "This is a sentence."

let areTheyEqual = (firstSentence == secondSentence)</pre>
<p>The variable &#8220;areTheyEqual&#8221; would then have a value of &#8220;true&#8221;.</p>
<h3>String Interpolation</h3>
<p>You have seen me use this before, but it should be stated here.  String interpolation lets you easily put values into Strings, so you could have something like this:</p>
<pre class="lang:swift decode:true">let length = 7
let width = 3

print("The rectangle has a length of \(length) and a width of \(width), giving it an area of \(length * width).")
//Outputs:  The rectangle has a length of 7 and a width of 3, giving it an area of 21.</pre>
<p>This works with many built in types, and as you saw here, even with expressions (the multiplication of the two variables, in this case).</p>
<h2>Conclusion</h2>
<p>Strings are a very important part of many programs, and Apple did a great job implementing Swift&#8217;s version of the String type.  While learning about Strings, we even got an introduction to initializers and the wildcard pattern, which are both other important aspects of Swift.  We will cover these more at a later date.  If you want to learn more about those, check my future posts <a href="http://www.codingexplorer.com/class-initializers/">Class Initializers</a> and <a href="http://www.codingexplorer.com/pattern-matching-in-swift/">Pattern Matching in Swift</a>.  While that post is named &#8220;Class initializers&#8221; and Strings are structs, all that is shown in that post works the same for structs.  There are some differences, but I don&#8217;t believe they are covered in that post.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftStrings">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-strings/">Swift Strings</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Type Casting in Swift</title>
		<link>https://www.codingexplorer.com/type-casting-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 14 Aug 2014 01:35:26 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=420</guid>

					<description><![CDATA[<p>In my previous post, Generic Functions in Swift, I used a type casting operator to check for inheritance.  It was simple enough to mention there, but I felt I should cover type casting in Swift a bit more in-depth in its own post.  Type casting is a way to convert an object of one type [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/type-casting-swift/">Type Casting in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In my previous post, <a title="Generic Functions in Swift" href="http://www.codingexplorer.com/generic-functions-in-swift/">Generic Functions in Swift</a>, I used a type casting operator to check for inheritance.  It was simple enough to mention there, but I felt I should cover type casting in Swift a bit more in-depth in its own post.  Type casting is a way to convert an object of one type to another.</p>
<p>There is one term that is used a lot when talking about type casting, so it should probably be defined upfront, that term is <strong>downcast</strong>.  According to <a title="Downcasting - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Downcasting">Wikipedia</a>, downcasting is the act of casting a reference of a base class to one of its derived classes.  There is an opposite term to this one, the obviously named <strong>upcast</strong>.  While this term is not used in Apple&#8217;s iBook, it is used in the WWDC video &#8220;Swift Interoperability In Depth.&#8221;  It of course means to go the other way, casting a derived class back up to one of its base classes.<br />
<span id="more-420"></span></p>
<h2>Swift&#8217;s Type Casting Operators</h2>
<p>There are 3 type casting operators in Swift with extremely simple names:  <span style="color: #bb2ca2;"> is</span>, <span style="color: #bb2ca2;"> as</span>?, and <span style="color: #bb2ca2;"> as</span>!.  One could make the argument that they are really 2, since the last two are the same operator with an optional and non-optional form.  Nonetheless, here is a handy table to show them all in one place and what they return:</p>
<table border="1">
<tbody>
<tr>
<td> Operator</td>
<td> Return Type</td>
</tr>
<tr>
<td><span style="color: #bb2ca2;"> is</span></td>
<td> Bool, if the entity is indeed one of its subclasses or adopts that protocol</td>
</tr>
<tr>
<td><span style="color: #bb2ca2;"> as</span>?</td>
<td> Optional of intended entity.</td>
</tr>
<tr>
<td><span style="color: #bb2ca2;"> as</span>!</td>
<td> Forcefully unwrapped optional of intended entity.</td>
</tr>
</tbody>
</table>
<p>This is just for a quick reference, let&#8217;s get a bit more in depth on what these actually do.</p>
<h3>The is Operator</h3>
<p>The <span style="color: #bb2ca2;">is</span> operator has two related but technically distinct uses in Swift.</p>
<p>First, if the right-hand term is a class name, it returns a Bool regarding whether the left-hand term is indeed that subclass.</p>
<p>Secondly, if the right-hand term is a protocol, it returns a Bool regarding whether the left-hand term adopts that protocol.</p>
<p>Another way of describing the <span style="color: #bb2ca2;">is</span> operator is that it returns a Bool whether the left-hand term can be downcast to a specific type.  Since protocols can also be treated as types (like making an array of <span style="color: #703daa;">Equatable</span> objects), this works the same for the protocol form.  So while what it does is semantically distinct between classes and protocols, they both boil down to whether you can downcast the left-hand term.</p>
<p>This <del>is</del> was actually a bit more nuanced than I thought.  I originally thought <span style="color: #bb2ca2;">is</span> just checked whether the cast would be possible, but there <del>was</del> more to it.  (<strong>Update:</strong>  Since the original writing of this post, now the <span style="color: #bb2ca2;">is</span> operator checks whether the cast is possible)  Take this example:</p>
<pre class="lang:swift decode:true">let controlArray = [UILabel(), UITextView(), UIButton()]

for item in controlArray {
    if item is UILabel {
        print("UILabel")
    }
    else if item is UITextView {
        print("UITextView")
    }
    else if item is UIButton {
        print("UIButton")
    }
    else if item is UIDatePicker {
        print("UIDatePicker")
    }
}</pre>
<p>It&#8217;s pretty simple, we just make a Swift array of three objects, a <span style="color: #703daa;">UILabel</span>, <span style="color: #703daa;">UITextView</span>, and a <span style="color: #703daa;">UIButton</span>.  To hold all of these elements, the compiler had to look for their common superclass, so <span style="color: #4f8187;">controlArray</span> is actually an array of <span style="color: #703daa;">UIView</span>s. Well, <span style="color: #703daa;">UIView</span>s are actually subclasses of <span style="color: #703daa;">NSObject</span>, so what if we add this case:</p>
<pre class="lang:swift decode:true">else if item is NSString {
    print("NSString")
}</pre>
<p>That should work, right? Nope, the compiler emits a warning that says &#8220;Cast from &#8216;UIView&#8217; to unrelated type &#8216;NSString&#8217; always fails.&#8221;  It lets it compile, but tells you that it will never be true, so you might as well just take it out.</p>
<p>One thing to note though, if we add another object to that array that is a subclass of <span style="color: #703daa;">NSObject</span>, then that <del>error</del> warning goes away, so if we changed the array to this:</p>
<pre class="lang:swift decode:true">let controlArray = [UILabel(), UITextView(), UIButton(), NSDate()]</pre>
<p>Now controlArray is actually an array of <span style="color: #703daa;">NSObject</span>s, so it is possible to downcast it to an <span style="color: #703daa;">NSString</span>.</p>
<p>Now okay, that might be obvious, but an <span style="color: #703daa;">NSString</span> is an <span style="color: #703daa;">NSObject</span>, this should <em>surely</em> work:</p>
<pre class="lang:default decode:true">var someString: NSString = "Old school"
var typeCheck = someString is NSObject  //Attempting to save a Bool to typeCheck
//Warning:  'is' test is always true</pre>
<p>Like the above test shows, this now works, but gives the compiler warning of &#8221; &#8216;is&#8217; test is always true &#8220;.  I am leaving the text above for historical purposes on how things used to be in Swift 1, it was interesting given how Swift worked at the time.  Now the  <span style="color: #bb2ca2;">is</span> operator acts a bit more like my original interpretation, checking whether the cast is possible, as opposed to just testing for downcasts.</p>
<h3>The as? Operator</h3>
<p>I&#8217;m going to start the other way around for this one and start with the optional form.  The <span style="color: #bb2ca2;">is</span> operator checks whether the downcast is possible, if we try to downcast the first element in the <span style="color: #4f8187;">controlArray </span>(a UILabel) to a <span style="color: #703daa;">UIDatePicker</span>, that would fail, since while they both are <span style="color: #703daa;">UIView</span>s, my UILabel was certainly not a <span style="color: #703daa;">UIDatePicker</span>.  As such, if it could fail, the program needs a way to signify that.  Sounds like a great use for Swift optionals once more!  So, let&#8217;s rewrite that <span style="color: #4f8187;">controlArray</span> for loop using some Optional Binding to take advantage of the unique aspects of these controls.</p>
<pre class="lang:swift decode:true">let controlArray = [UILabel(), UIButton(), UIDatePicker()]

for item in controlArray {
    if let someLabel = item as? UILabel {
        let storeText = someLabel.text
    }
    else if let someDatePicker = item as? UIDatePicker {
        let storeDate = someDatePicker.date
    }
}</pre>
<p>So now, our for loop steps through our controlArray, and grabs pertinent data out of some controls we care about, and ignores the ones we don&#8217;t.  It will grab the text from the <span style="color: #703daa;">UILabel</span>, the date from the <span style="color: #703daa;">UIDatePicker</span>, and just ignore the <span style="color: #703daa;">UIButton</span> altogether.  Now, I&#8217;m not doing anything with those values here to just keep the code concise to show off the Optional Binding, but you could store those elsewhere in more permanent variables if you wanted.</p>
<p>Nonetheless, that is how that works, the <span style="color: #bb2ca2;">as</span><span style="color: #000000;">? operator returns an optional, and then we use optional binding to assign it to a temporary constant, and then use that in the if clause.</span></p>
<h3>The as! Operator</h3>
<p>There is not too much more to say here, but as operator is the forcefully unwrapped optional form of the <span style="color: #bb2ca2;">as</span><span style="color: #000000;">? operator.  To forcefully type something that you believe cannot fail, you use the <span style="color: #bb2ca2;">as</span>! operator, which is now consistent with how Swift&#8217;s Optional Syntax works in all other situations.  As with any force unwrapping though, using the <span style="color: #bb2ca2;">as</span>! operator risks runtime errors that will crash your app should the unwrapping not succeed.</span></p>
<p>You should only use this one if you are certain that the downcast would be successful.  You would use it like so:</p>
<pre class="lang:swift decode:true">let aControlThatShouldBeAButton: UIView = UIButton()
let thatButton: UIButton = aControlThatShouldBeAButton as! UIButton</pre>
<p>One thing to note, <strong>upcasting</strong> is often done implicitly.  As the first line shows, the <span style="color: #703daa;">UIButton</span> was just created, and then assigned directly to the explicitly typed <span style="color: #703daa;">UIView</span> &#8220;aControlThatShouldBeAButton.&#8221;  You can use <span style="color: #bb2ca2;">as</span> to upcast if you wish to not write the type on the left side, but it is probably best practice to write it with normal typing as shown on the first line in the above example for upcasting.</p>
<p>The original <span style="color: #bb2ca2;">as</span> operator does still exist, but it has a much more narrow use.  The only times I&#8217;ve seen it somewhat required, is when you need to typecast to a bridged type when the typecasting is not implicit.  For instance, a few releases ago NSString would no longer implicitly convert to a Swift String.  Swift Strings would still implicitly convert to NSString when necessary, but you could not go the other way around implicitly.  In that case, to convert an NSString to a Swift String, now you use the original <span style="color: #bb2ca2;">as</span> operator.  It is basically used for type conversions that the compiler can be certain will succeed, like converting Bridged types.  It also apparently can work for upcasts, though I have not seen that documented anywhere, but was confirmed in a playground in the version of Xcode mentioned at the bottom of this article.  So the above statement is still correct, about using the original <span style="color: #bb2ca2;">as</span> operator to upcast a UIButton to a UIView, if you don&#8217;t want to explicitly type &#8220;aControlThatShouldBeAButton&#8221;.</p>
<h2>Conclusion</h2>
<p>I thought this post was going to be a lot simpler when I started it, but I learned quite a bit when testing this out in the playgrounds.  My key take-aways from this article (that weren&#8217;t immediately obvious) are:</p>
<ul>
<li>The <span style="color: #bb2ca2;">is</span> operator checks whether an entity can be <strong>downcast</strong> to a type in the same hierarchy.  <del>It does <strong>not</strong> check for upcasting.</del></li>
<li><strong>Upcasting</strong> is done implicitly.</li>
</ul>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftTypeCasting">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/type-casting-swift/">Type Casting in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Generic Functions in Swift</title>
		<link>https://www.codingexplorer.com/generic-functions-in-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 11 Aug 2014 10:56:25 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=414</guid>

					<description><![CDATA[<p>Now, with knowledge of Protocols in Swift in hand, let&#8217;s get to talking about one of the other big additions to the Swift language:  Generics.  I had previously discussed in my post Swift Optionals – Declaration, Unwrapping, and Binding how Swift optionals work under the hood.  In that case, the OptionalValue enum is a generic type.  Today we [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/generic-functions-in-swift/">Generic Functions in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Now, with knowledge of <a title="Protocols in Swift" href="http://www.codingexplorer.com/protocols-swift/">Protocols in Swift</a> in hand, let&#8217;s get to talking about one of the other big additions to the Swift language:  Generics.  I had previously discussed in my post <a title="Swift Optionals – Declaration, Unwrapping, and Binding" href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals – Declaration, Unwrapping, and Binding</a> how Swift optionals work under the hood.  In that case, the OptionalValue enum is a generic type.  Today we are going to cover a slightly easier aspect of generics, generic functions.  Generic functions are functions that can take parameters of any type (with or without constraints based on protocol adoption), and perform some action with them.<br />
<span id="more-414"></span></p>
<h2>A Fully Generic Function</h2>
<p>How would you check if an arbitrary object is an Objective-C object?  For the most part, you would have to check if it inherits from NSObject.  Anytime I read introduction to Objective-C object texts, they will say that <em>almost</em> all objects inherit from NSObject.  I have yet to find one that does not for Objective-C myself, but just in case, I had to give that disclaimer.</p>
<hr />
<p><strong>Update:</strong>  Reader <a title="Doug Knowles (@dougknowles76) | Twitter" href="https://twitter.com/dougknowles76">Doug Knowles</a> has <a title="Doug Knowles on Twitter: &quot;@CodingExplorer Example of ObjC class that is not an NSObject: NSProxy. (Only one I know of.) (And thanks for #Swift posts!)&quot;" href="https://twitter.com/dougknowles76/status/498898552291340288">pointed out</a> (sorry that the update of this is MUCH later) to me that at least ONE class does not inherit from NSObject.  The caveat to this is that it adopts the NSObjectProtocol, which, when conformed to, makes it act much like a real object.  I din&#8217;t know much about NSProxy personally, but the <a title="NSProxy Class Reference" href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSProxy_Class/index.html">documentation</a> says that an NSProxy object basically stands-in for a real object that has yet to exist.  I&#8217;m thinking that NSProxy probably won&#8217;t be used much in Swift, seems a bit more dynamic than Swift prefers to be, but hey, at least we know probably the only Objective-C class that does not inherit from NSObject!</p>
<hr />
<p>Anyway, here is a function that can take any object, and then returns a Bool describing whether the object inherits from NSObject:</p>
<pre class="lang:swift decode:true">func isAnNSObject&lt;T&gt;(_ someObject: T) -&gt; Bool {
    if someObject is NSObject {
        return true
    } else {
        return false
    }
}</pre>
<p>I am using a new operator there that I have not used before.  The &#8220;is&#8221; operator checks if a value is of a certain type (or inherits from it).  You can read more about this operator on the post <a title="Type Casting in Swift" href="http://www.codingexplorer.com/type-casting-swift/">Type Casting in Swift</a>.</p>
<p>So for this function, I am checking if &#8220;someObject&#8221; is an NSObject (or at least inherits from it).  If it is, the function returns true, if it is not, it returns false.</p>
<p>After the name of the function, you see a &lt;T&gt;.  The &#8220;T&#8221; in the angle brackets is a placeholder name for a type.  The function prototype then says that the input parameter must be of that type.  That&#8217;s all there is to it for a simple generic function.  We only have one parameter in this function, but if we had multiple, we would state that the parameters must be of the same type by giving them both the same type placeholder (&#8220;T&#8221; in this case).  If they can be other types, then different placeholder values can be used for the different types.</p>
<p>We then use this function like any other function.  As far as calling a generic function goes in Swift, there is no difference, you just give it the arguments like normal.  Here is a simple test of that function:</p>
<pre class="lang:swift decode:true">class BlankClass {
}

let objcObject = NSDate()
let swiftObject = BlankClass()

isAnNSObject(objcObject)    //returns "true"
isAnNSObject(swiftObject)   //returns "false"</pre>
<p>&nbsp;</p>
<h2>Generic Function with Type Constraints</h2>
<p>That&#8217;s all well and good, but there are only a few times you would ever be able to take absolutely ANY kind of value, you usually have to give your generic function some constraints.  For instance, you could make a function that returns the maximum value of two Ints or Doubles that you put into it, like these functions:</p>
<pre class="lang:swift decode:true">func maximumInt(_ first: Int, _ second: Int) -&gt; Int {
    
    if (first &gt;= second) {
        return first
    }
    
    return second
}

func maximumDouble(_ first: Double, _ second: Double) -&gt; Double {
    
    if (first &gt;= second) {
        return first
    }
    
    return second
}</pre>
<p>Those are well and good too, but they only take Ints and Doubles.  This sounds like the perfect time for a generic function!  But we couldn&#8217;t just let it take ANY class and return that.  If we made a fully generic function that had no constraints, and give it a couple of objects of some arbitrary class I make up like &#8220;Car&#8221;, and tell it to give me the maximum&#8230; What does it do?  Which is the maximum &#8220;Car&#8221; object?</p>
<p>This is where type constraints come in.  Remember in <a title="Protocols in Swift" href="http://www.codingexplorer.com/protocols-swift/">Protocols in Swift</a>, we talked about whether a class was <span style="color: #703daa;">Equatable</span> or not?  There is another protocol that is much much more useful here, the <span style="color: #703daa;">Comparable</span> protocol.</p>
<p>Swift&#8217;s <span style="color: #703daa;">Comparable</span> protocol itself inherits from the <span style="color: #703daa;">Equatable</span> protocol, and has a requirement of its own.  To conform to the <span style="color: #703daa;">Comparable</span> protocol itself, you must implement the less-than &#8220;&lt;&#8221; operator.  Then to conform the the inherited <span style="color: #703daa;">Equatable</span> protocol, the class must implement how the &#8220;==&#8221; operator applies to that class.  Once you implement both of those requirements, you automatically get the use of &gt;, &lt;=, and &gt;= (since they are just combinations of the two you <em>did</em> implement with some boolean NOTs mixed in).</p>
<p>With that in mind, here is how we make a Generic form of our maximumInt and maximumDouble functions:</p>
<pre class="lang:swift decode:true">func maximumValue&lt;T: Comparable&gt;(_ first: T, _ second: T) -&gt; T {
    
    if (first &gt;= second) {
        return first
    }
    
    return second
}</pre>
<p>One thing to note, the method body is the exact same between all three functions.  They don&#8217;t really need the type information inside, as long as they are the same and conform to the <span style="color: #703daa;">Equatable</span> protocol.</p>
<p>We verify that the type conforms to the <span style="color: #703daa;">Comparable</span> protocol by basically treating that protocol as a type of the placeholder type name, as you see:</p>
<pre class="lang:swift decode:true ">&lt;T: Comparable&gt;</pre>
<p>Doesn&#8217;t that look an awful lot like the name of a variable (in this case &#8220;T&#8221;), and the type of that variable (in this case &#8220;<span style="color: #703daa;">Comparable</span>&#8220;)?  While I&#8217;m not certain if that was intended, it&#8217;s certainly a good way to remember how this syntax works in Swift.</p>
<p>We then verify that our two values &#8220;first&#8221; and &#8220;second&#8221; both are the same type &#8220;T&#8221;, and then we will return type T.  So now we can use this for Ints, Doubles, or any types that conform to the <span style="color: #703daa;">Comparable</span> protocol.</p>
<h3>Using a Custom Class with our Constrained Generic Function</h3>
<p>I don&#8217;t know how to objectively compare &#8220;Cars&#8221; like my earlier idea suggests, but let&#8217;s compare something more objective, like a contestant of a game show.  They have a score, which you can compare, so let&#8217;s make a contestant class:</p>
<pre class="lang:swift decode:true">class Contestant {
    var name: String
    var score = 0

    init(name: String) {
        self.name = name
    }
}

extension Contestant: Comparable {
    static func &lt; (lhs: Contestant, rhs: Contestant) -&gt; Bool {
        return lhs.score &lt; rhs.score
    }

    static func == (lhs: Contestant, rhs: Contestant) -&gt; Bool {
        return lhs.score == rhs.score
    }
}</pre>
<p>Now, there are some new things in here, like operator overloading.  At least for the <span style="color: #703daa;">Comparable</span> protocol, you have to give these operators functions at the global scope (so outside of the class).  In this case, I just wanted to compare contestants by their score.  You can read more about operator overloading in the post <a title="Operator Overloading — Tailor Swift To Your Needs" href="http://www.codingexplorer.com/swift-operator-overloading/">Operator Overloading — Tailor Swift To Your Needs</a>.</p>
<p>Now yes, we could just compare their scores, but then we would get the maximum score returned, not the object with the maximum score.  This way, we can just compare contestants, and it will look inside the Contestant object, and compare their scores, so we would use our new function like this:</p>
<pre class="lang:swift decode:true">let Lee = Contestant(name: "Lee")
let Roy = Contestant(name: "Roy")

Lee.score = 3
Roy.score = 7

let winner = maximumValue(Lee, Roy)

print(winner.name)
//Outputs "Roy"
</pre>
<p>There&#8217;s our own custom class that adopts the <span style="color: #703daa;">Comparable</span> protocol, and works with our generic function to see who has the highest score.  Now that is quite useful!</p>
<h2>Conclusion</h2>
<p>Generics are a very powerful tool in Swift.  In this post, we&#8217;ve seen how they allow you to make a single function to handle multiple types, as long as the conform to some appropriate constraints.  We have not even touched the concept of generic types yet (but we do later, in the post <a title="Generic Types in Swift" href="http://www.codingexplorer.com/generic-types-swift/">Generic Types in Swift</a>), but you probably have worked with them already.  The Swift <a title="Arrays and their Methods in Swift" href="http://www.codingexplorer.com/arrays-swift/">Array</a> and <a title="Swift Dictionary Quick Reference" href="http://www.codingexplorer.com/swift-dictionary-quick-reference/">Dictionary</a> types are actually generic type collections under the hood.</p>
<p>One thing to note, similar to the &#8220;swap&#8221; example in Apple&#8217;s Swift iBook, we reimplemented something that already exists in Swift for an example.  Swift&#8217;s standard library already has a function named &#8220;max&#8221; that does this for us.  So, while we can implement one of our own, you might as well use the built in one.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftGenericFunctions">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/generic-functions-in-swift/">Generic Functions in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Protocols in Swift</title>
		<link>https://www.codingexplorer.com/protocols-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 09 Aug 2014 06:54:44 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<category><![CDATA[properties]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=401</guid>

					<description><![CDATA[<p>I wanted to write a bit about Generics in Swift, but I realized that some of the major powers of Generics require the use of protocols, so I felt I should start by talking about them first. In Swift, protocols are basically a named contract that your classes can conform to.  If your class says [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/protocols-swift/">Protocols in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I wanted to write a bit about Generics in Swift, but I realized that some of the major powers of Generics require the use of protocols, so I felt I should start by talking about them first.</p>
<p>In Swift, protocols are basically a named contract that your classes can conform to.  If your class says it conforms to <span style="color: #703daa;">Equatable</span>, then it better fulfill all of the required functionality to make it equatable.  They are rather similar to interfaces in C# or Java.  They list off the function prototypes and variable declarations, as well as stating whether they are required or optional, but don&#8217;t actually do anything.  It is up to class, structs, or enumerations that claim to conform to the protocol to actually provide the functionality.</p>
<h2>Defining a Protocol</h2>
<p>This is pretty easy.  It is very much like defining a class in Swift, except you write <span style="color: #bb2ca2;">protocol</span> instead, observe:</p>
<pre class="lang:swift decode:true">protocol Vehicle {
    //Functions and properties prototypes go here.
}</pre>
<p>Then you just fill it with what you want.<br />
<span id="more-401"></span></p>
<h2>Protocol Adoption by classes, structs, and enumerations</h2>
<p>In Swift, when you declare your class, if you want it to have a superclass, you follow the class name with a colon, and then the name of that superclass.  If you want it then to conform to some protocols, you then follow that superclass with a comma, and then the name of the protocol.  In my opinion, this makes it less obvious what is the superclass and what is a protocol.  Nonetheless though, the current way to adopt a protocol is shown below:</p>
<pre class="lang:swift decode:true">class UserCar:  PlayableCharacterSuperclass, Vehicle {
    //Function and property implementations go here.
}</pre>
<h2>Declaring Requirements</h2>
<p>Now that we have the protocol&#8217;s shell made, we now need to write what that protocol requires.  These can be either properties or methods.</p>
<h3>Protocol Properties</h3>
<p>Firstly, properties in protocols must always be variables, and cannot be constants.  This doesn&#8217;t mean that they must all be writeable, but as far as the declaration, they must be <span style="color: #bb2ca2;">var</span> in the protocol.  In Swift 1.1, constants must have their values given when they are created, so this makes sense (because protocols cannot implement that, only give it a name, type, and list of capabilities).  Swift 1.2 has changed some of these rules about constants, but does not seem to have changed this requirement for protocols so far.  To determine whether it is writeable or not, you append either { <span style="color: #bb2ca2;">get set</span> } or { <span style="color: #bb2ca2;">get</span> }, as shown below:</p>
<pre class="lang:swift decode:true">protocol Vehicle {
    var numberOfWheels: Int { get }     //readonly
    var color: UIColor { get set }      //read-write
}</pre>
<p>This does not necessarily mean they have to be <span style="color: #bb2ca2;">var</span> inside the class that implements them though.  It just has to be able to do what is requested.  If you want numberOfWheels to be settable inside the class, then you can use a <span style="color: #bb2ca2;">var</span> as it requests here.  However, if it is just a constant defined only once, a <span style="color: #bb2ca2;">let</span> constant can be used in the actual class, since it fulfills the &#8220;get&#8221; capability.</p>
<p>The &#8220;color&#8221; property is { <span style="color: #bb2ca2;">get set</span> }, so it must be settable and thus must be a var in the class that conforms to this protocol.</p>
<h3>Protocol Methods</h3>
<p>As mentioned before, to define a method in a protocol you just define its prototype (just the first line with the name, parameters, and return types).  For a simple method, you would define it like this:</p>
<pre class="lang:swift decode:true">func renderImageOfCar() -&gt; UIImage</pre>
<p>There is a caveat though.  Classes are reference types.  When you assign a <strong>reference</strong> type to a new variable, you just pass a reference to that instance of it, so if you change the first variable that instance was assigned to, you will change what both variables are connected to.  When you assign a <strong>value</strong> type to a new variable, the whole thing is copied to put there.  Structs and enumerations are value types.</p>
<p>If you want to actually change member variables of a struct, you must precede a function with the keyword &#8220;mutating&#8221;.  If you want your protocol to work on value AND reference types when mutating instance variables, you must add mutating to the protocol&#8217;s method prototype.</p>
<pre class="lang:swift decode:true">mutating func drive()</pre>
<p>You do not need mutating before functions that mutate member variables in classes.  While you must write mutating in your protocol if you want it to work with classes, structs, and enumerations, you do not actually have to write mutating before the function&#8217;s actual implementation if you are writing a class.  You still do for the structs and enumerations though.</p>
<h2>Required and Optional Elements in Protocols</h2>
<p>First things first, by default in Swift, anything in a protocol is required.  If you just do what you&#8217;ve seen earlier in this article, you will have made those properties and methods required.</p>
<p>You have 2 choices to make them optional, both have pros and cons.</p>
<p>Irrelevant of which way you do it though, you can call them via Swift&#8217;s optional chaining, since the whole point is the user may not have implemented them.  You have to know if they are valid in some fashion, so you can treat either way like a Swift optional to know.</p>
<h3>Objective-C style Protocol Optional Requirements</h3>
<p>This is the reimplementation of the classic way to make a protocol requirement optional.  You have to do 2 things:  precede your protocol declaration with <span style="color: #bb2ca2;">@objc</span>, and precede your function or variable declaration with <span style="color: #bb2ca2;">optional</span> like so:</p>
<pre class="lang:swift decode:true">@objc protocol driveableProtocol {
    @objc optional var unimportantNumber: Int { get set }
}</pre>
<p>When it is declared like this, if your class implements the DriveableProtocol, it does not have to mention unimportantNumber anywhere.   It can if you think it should, but it does not have to.  There are some caveats to this though.  I did say if your class implements this on purpose.  If you use <span style="color: #bb2ca2;">@objc</span>, it MUST be a class, you cannot use an <span style="color: #bb2ca2;">@objc</span> protocol for enumerations or structs in Swift.</p>
<p>This is not the only place you ever use <span style="color: #bb2ca2;">@objc</span>.  I don&#8217;t want to get into it much here, but it generally tells the compiler that what you declared is available to use in Objective-C code.  Unfortunately though you have to use it in protocols for optional requirements even if you don&#8217;t touch Objective-C.</p>
<h3>Swift style Protocol Optional Requirements</h3>
<p>Since you have to treat these optional requirements with Swift&#8217;s optional syntax anyway&#8230;. why not use Swift optionals?  If you do it this way, you do not need to use the <span style="color: #bb2ca2;">@objc</span> at the beginning, so you can still use your protocol for structs and enumerations.  The downside is that your class/struct/enumeration must implement it, but can just declare it as an optional and just leave it set to nil.</p>
<p>You would just create your required optional requirements (sounds weird to say, but accurate in this case) in this way:</p>
<pre class="lang:swift decode:true">protocol somethingProtocol {
    var someString: String? { get set }
    
    func doSomething(inputA: Int) -&gt; String?
}</pre>
<p>In the case of the function, you do have to implement it, but you can just have it return nil.  If you have a function without return values, you can just leave the function body blank when implementing it.  It is inelegant, but it is another way to have optional functionality in protocols, that lets you just stay in the land of Swift, and not have to break its functionality with structs and enumerations.</p>
<h2>Conclusion</h2>
<p>There are definitely more aspects about protocol in Swift to talk about, but I felt these were the most important.  With this you can create them, implement them, and make some requirements optional.  They are quite useful when you want to decouple your code from requiring a specific class.  If you want to compare different values, you could have multiple methods like compareStrings, compareInts, compareDoubles, or you could just use the &#8220;==&#8221; operator.  The <span style="color: #703daa;">Equatable</span> protocol requires that the class implement that operator.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftProtocols">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/protocols-swift/">Protocols in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Nil Coalescing in Swift</title>
		<link>https://www.codingexplorer.com/nil-coalescing-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 05 Aug 2014 19:05:53 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=365</guid>

					<description><![CDATA[<p>Xcode Beta 5 was released with several good changes.  I don&#8217;t want this to just be a &#8220;What&#8217;s new in Xcode Beta 5&#8221; post, because once Beta 6 is released, much less the real language, the only point for a post like that is history.  So I am mostly going to talk about my favorite addition [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/nil-coalescing-swift/">Nil Coalescing in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Xcode Beta 5 was released with several good changes.  I don&#8217;t want this to just be a &#8220;What&#8217;s new in Xcode Beta 5&#8221; post, because once Beta 6 is released, much less the real language, the only point for a post like that is history.  So I am mostly going to talk about my favorite addition to Xcode 6 about optionals, with a short mention of a change that affects it.  This great operator is still available in Swift 2.2 (Xcode 7.3) as well!</p>
<h2>Nil Coalescing Operator</h2>
<p>I did not see this one coming, but I do like it.  It basically is a way to easily return an unwrapped optional, or a default value.  As with many other parts of optionals, this operator is composed of question marks.  Below is a simple example:</p>
<pre class="lang:swift decode:true">var someOptional: Int? = nil
var aDefaultValue = 42

var theAnswer = someOptional ?? aDefaultValue</pre>
<p>Since someOptional is nil (we didn&#8217;t set it to a valid Int yet), theAnswer will of course be 42.<br />
<span id="more-365"></span><br />
Apple&#8217;s iBook shows that the nil coalescing operator is shorthand for a ternary operator.  While I can use the ternary operator and it is a short and concise way of writing a simple conditional, I usually have to look it up just to be sure, so for simplicity, I am going to compare it to what the ternary operator itself is shorthand for:</p>
<pre class="lang:default decode:true">if (someOptional != nil) {
    theAnswer = someOptional!
} else {
    theAnswer = aDefaultValue
}</pre>
<p>That is effectively what the nil coalescing operator is doing.  Upon writing that, I can see why they chose to use the ternary operator, much shorter, and didn&#8217;t need me to write &#8220;theAnswer =&#8221; twice .  Nonetheless, I still find it clearer to read.  For the sake of historical significance, this is from the release notes, and appears to be the function definition for the nil coalescing operator:</p>
<pre class="lang:swift decode:true">public func ?? &lt;T&gt;(optional: T?, defaultValue: @autoclosure () throws -&gt; T) rethrows -&gt; T {
    switch optional {
    case .some(let value):
        return value
    case .none:
        return try defaultValue()
    }
}</pre>
<p>That is from Open Source Swift&#8217;s code.  It is a bit different from the first version, but mostly to move @autoclosure to its new place, and the ability to handle throwing errors.  There is a slight modification, the &#8220;Some&#8221; and &#8220;None&#8221; are lowercase in the Open Source repository, but that is probably just how it looks internally.  There is also a version of this in the standard library that handles the error handling with the T type marked as optional.  Since the optional is actually an enumeration (as mentioned in my post <a title="Swift Optionals – Declaration, Unwrapping, and Binding" href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals – Declaration, Unwrapping, and Binding</a>), it being a switch statement internally is more likely.  I did not know exactly what autoclosure did, but Jameson Quave did, so to quote him here, &#8220;the right-hand side takes basically any expression (any closure, except you don’t need to specify it’s a closure, the @autoclosure keyword turns it in to one).&#8221;  See his original article at <a title="Swift's Nil Coalescing Operator In Xcode 6 Beta 5 | iOS Swift Development Tutorials by Jameson Quave" href="http://jamesonquave.com/blog/swifts-nil-coaelescing-operator-in-xcode-6-beta-5/">Swift’s Nil Coalescing Operator In Xcode 6 Beta 5</a>.  We have not really talked about closures yet, but they are one of the big additions to Swift, and they are basically self-contained code blocks.  I would say they are kind of like functions, but able to be passed around like they were a variable, but it turns out, according to Apple&#8217;s iBook, functions are a special type of closure.</p>
<p>One other thing to note is that the second term, the &#8220;aDefaultValue&#8221;, is lazily evaluated.  If it was a function there instead of a variable, it would not run the function unless the someOptional was nil.  If it isn&#8217;t, then it just uses the unwrapped form of the variable, and just goes to the next line of code.  That makes sense to me, better to not waste time evaluating something you won&#8217;t use.</p>
<h2>Change to Optional protocol conformance</h2>
<p>There was a breaking change to how optionals are handled in Swift.  You may have noticed earlier in the if statement explanation of the nil coalescing operator, that I checked it against nil.  Previously, optionals conformed to the LogicValue protocol (which was later renamed BooleanType).  That meant you could use an optional as if it were a boolean (if there was a value, it was true, if there was a nil, it was false).  That is no longer the case, the optional must be compared against nil instead.  This unfortunately invalidated some of the slides from WWDC, but they did say there would be a lot of changes, and not necessarily have source compatibility between seeds.</p>
<p>That being said though, optional binding still works with the &#8220;if let&#8221; syntax.  Optional chaining works as well, but if it is in an if statement, it must either be optionally bound, or checked against nil.</p>
<h2>Conclusion</h2>
<p>That is how the nil coalescing operator works.  It is basically an easier to read ternary statement, which itself is a more concise if statement.  Each of those analogies though are apparently covering up a switch statement.  Abstraction!</p>
<p>With changes coming to Swift every few months, I&#8217;m always going back to check my previous posts, and updating them when necessary.  The price we pay for blogging on the frontier.</p>
<p>Also, while it is unlikely that you have seen my blog before Jameson&#8217;s, if that somehow is the case, check out his blog at <a title="Jameson Quave Austin iOS Developer and Entrepreneur" href="http://jamesonquave.com/blog/">http://jamesonquave.com/blog/</a>.  He definitely knows his Swift stuff and has definitely been helpful to the new Swift community.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-NilCoalescing">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Swift's Nil Coalescing Operator In Xcode 6 Beta 5 | iOS Swift Development Tutorials by Jameson Quave" href="http://jamesonquave.com/blog/swifts-nil-coaelescing-operator-in-xcode-6-beta-5/">Swift’s Nil Coalescing Operator In Xcode 6 Beta 5</a></li>
<li>Xcode 6 Beta 5 Release Notes</li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/nil-coalescing-swift/">Nil Coalescing in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Enumerations in Swift</title>
		<link>https://www.codingexplorer.com/enumerations-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 01 Aug 2014 21:58:34 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=356</guid>

					<description><![CDATA[<p>I have mentioned enumerations in three previous posts (Computed Properties in Swift, Swift Optionals – Declaration, Unwrapping, and Binding, and Loops, Switch Statements, and Ranges in Swift).  It is probably about time to actually talk about them, eh?  In C, and even Objective-C, enumerations were little more than glorified aliases for integer values.  In Swift though, [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I have mentioned enumerations in three previous posts (<a title="Computed Properties in Swift" href="http://www.codingexplorer.com/computed-properties-in-swift/">Computed Properties in Swift</a>, <a title="Swift Optionals – Declaration, Unwrapping, and Binding" href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals – Declaration, Unwrapping, and Binding</a>, and <a title="Loops, Switch Statements, and Ranges in Swift" href="http://www.codingexplorer.com/loops-switch-statements-ranges-swift/">Loops, Switch Statements, and Ranges in Swift</a>).  It is probably about time to actually talk about them, eh?  In C, and even Objective-C, enumerations were little more than glorified aliases for integer values.  In Swift though, enumerations have been given significantly more power.  In Swift, enumerations are a lot more like classes or structs, on top of the actual enumeration values themselves.  For the moment though, we will talk about what makes an enumeration an enumeration.<br />
<span id="more-356"></span><br />
<a name="DeclareDefineEnums"></a></p>
<h2>Declaring and Defining Enumerations</h2>
<p>First thing&#8217;s first, how do you declare an enumeration in Swift?  You use the enum keyword, the name of the enumeration, and put a series of cases inside the enumeration&#8217;s curly braces (somewhat similar to a switch statement), like so:</p>
<pre class="lang:swift decode:true">enum LevelProgress {
    case Completed
    case AttemptedButIncomplete
    case Unattempted
}</pre>
<p>Back in the article <a title="Swift Optionals – Declaration, Unwrapping, and Binding" href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals – Declaration, Unwrapping, and Binding</a>, I had mentioned that enumerations can have associated values, in that case being the value that the optional was encapsulating.  So this enum was actually written to show those off a bit.  If we had a game that showed icons for the levels, and have them change based on how far the player has been, we could rewrite the above enumeration like this:</p>
<pre class="lang:swift decode:true">enum LevelProgress{
    case Completed(Int)
    case AttemptedButIncomplete(Double, NSDate)
    case Unattempted
}</pre>
<p>So for this I had a Completed state (with the number of stars earned), an AttemptedButIncomplete state (with the percentage complete and the date last attempted), and an Unattempted case (with no values), since they haven&#8217;t even tried it.  You would then assign it to a variable like this:</p>
<pre class="lang:swift decode:true">var level1 = LevelProgress.Completed(3)</pre>
<p>Also, if the type can be inferred with Swift&#8217;s type inference, you don&#8217;t even need to use the name of the enum (in this case LevelProgress).  You do have to if it cannot be easily inferred.  If it is already defined as a LevelProgress type, the name of the enum can be omitted, so you can do this:</p>
<pre class="lang:swift decode:true">var level1 = LevelProgress.Completed(3)
level1 = .AttemptedButIncomplete(0.75, testDate)</pre>
<p>Where you defined it as a valid enumeration variable once, or you could explicitly give it a type like this:</p>
<pre class="lang:swift decode:true">var level2 : LevelProgress
level2 = .Completed(3)</pre>
<p>Also, if a function parameter is of a certain type, like LevelProgress, you also can omit the name of the enum, since only a value of that type can be used as that argument.  So, if we had a function signature like this:</p>
<pre class="lang:swift decode:true">func printLevelDetails(level: LevelProgress)</pre>
<p>We could call it with an instance of type levelProgress, or we could just send the value in directly:</p>
<pre class="lang:swift decode:true">printLevelDetails( .Completed(3) )</pre>
<p><a name="LabelledEnumInits"></a></p>
<h3>Labelled Enumeration Initializers</h3>
<p>Now, I couldn&#8217;t find anything in the Apple iBook <a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftEnumerations">The Swift Programming Language</a>, nor really online about this, but I thought that similar to classes, you would be be able to name these inputs.  If nothing else, it should make it more readable.  Well, at least from messing around on a playground, it appears like you can, so I rewrote this like so:</p>
<pre class="lang:swift decode:true">enum LevelProgress {
    case Completed(stars: Int)
    case AttemptedButIncomplete(percentComplete: Double, lastAttemptedDate: NSDate)
    case Unattempted
}</pre>
<p>If I try to instantiate these states without those labels, the playground complains and suggests adding the labels in, as it should, so maybe an undocumented feature in Swift?  Who knows, but its there.  If I had to guess, it probably is calling an internal init method to assign this enumeration to a variable, but I have no evidence of this yet.  Since initializers can give their input parameters labels, this seems to make sense to me.  This may be a side effect, and there may be a reason they don&#8217;t mention it in the iBook, so, use it at your own risk.  This appears to still work as of Xcode 7.3.1.</p>
<p>For this style, you would then assign it to a variable like this:</p>
<pre class="lang:swift decode:true">let level1 = LevelProgress.Completed(stars: 3)</pre>
<h2>Using Enumerations</h2>
<p>So, as I mentioned in <a title="Loops, Switch Statements, and Ranges in Swift" href="http://www.codingexplorer.com/loops-switch-statements-ranges-swift/">Loops, Switch Statements, and Ranges in Swift</a>, enumerations are particularly useful in switch statements.  As mentioned in that article, switch statements must be exhaustive, so it must cover all of the enumeration states, or define a default state to do so.  So as such, let us give some functionality to that function I mentioned at the end of the <a href="#DeclareDefineEnums">Declaring and Defining Enumerations</a> section. In it we have a switch statement that also takes advantage of the associated values.</p>
<pre class="lang:swift decode:true">func printLevelDetails(level: LevelProgress) {
    switch level {
    case .Unattempted:
        print("Didn't attempt")
    case .AttemptedButIncomplete(let percentComplete, let lastAttemptedDate):
        print("About \(percentComplete) complete, last tried \(lastAttemptedDate).")
    case .Completed(let stars):
        print("Complete with \(stars) stars.")
    }
}</pre>
<p>So, basically, your switch statement runs through each case of the enum, and does something based off of it.  In this case, for the AttemptedButIncomplete and Completed states, it then binds the associated values to a variable that we then use in the println call.  All you have to do to bind it to a variable is to say &#8220;let newVariableName&#8221; for each value, in the order they are used.</p>
<p>I have used this a few times, but not explicitly stated it, that &#8220;\(someVariable)&#8221; notation is a shorthand in Swift for printing the string representation of a variable.</p>
<p>Without using an NSNumberFormatter, the output for .AttemptedButIncomplete is rather ugly, for example:  &#8220;About 0.75 complete, last tried 2014-08-01 20:09:58 +0000.&#8221;  It does get the point across for how to use it though.</p>
<p>One thing to note, if you try the labelled associated value names mentioned in the <a href="#LabelledEnumInits">last section</a>, these are NOT the same.  As of yet, I have not seen a way to use those labels to get the values back out explicitly through the label.  These are completely different names that do not interact with them at all, according to my testing.</p>
<h2>Raw Values For Enumerations</h2>
<p>There are cases when you need values with your enumeration states, but not the full flexibility of associated values.  You can use raw values if:</p>
<ul>
<li>Each case will have only 1 value.</li>
<li>That value will be the same type for each.</li>
<li>That value can be pre-populated in the enumerations definition.</li>
<li>That value will be unique for each case.</li>
<li>That value is a literal (so a String, Character, or the built in Integer and Floating-Point types).</li>
</ul>
<p>As an extra, if an Integer is used, it will auto-increment for each value if it is not explicitly defined.</p>
<p>This is Swift&#8217;s way of implementing enumerations in a way more consistent to how they were in C or Objective-C</p>
<h3>Defining an Enumeration with Raw Values</h3>
<p>This is actually pretty easy.  You basically give the enum a type after its name (like you would for a variable), and then equate the case names to a literal of some sort, so:</p>
<pre class="lang:swift decode:true">enum FirstYearOfDecade: Int {
    case Seventies = 1970
    case Eighties  = 1980
    case Nineties  = 1990
}</pre>
<p>This follows all of the conventions mentioned above.  Each has one value (the first year of that decade), they are all the same type (Int), they were pre-populated in the definition, they are unique, and each set to a literal (in this case an Integer Literal).</p>
<h3>Using the Raw Type</h3>
<p>Apple made this pretty easy with a simple property to read it, and the singular parameter to write it.</p>
<p>So to read the raw value, we could do either of these:</p>
<pre class="lang:swift decode:true">FirstYearOfDecade.Eighties.rawValue

let instantiatedDecade = FirstYearOfDecade.Seventies
instantiatedDecade.rawValue</pre>
<p>The first returns the integer associated with the &#8220;Eighties&#8221; case.  The second one assigns the &#8220;Seventies&#8221; case to a constant, and then we ask that constant to return the raw value with .rawValue.</p>
<p>To create a value from a raw value, you create it through an initializer.  These initializers are actually failable initializers, so they return an optional, since you may not always find a valid value from the raw version.  For example, this enumeration is actually talking about the first year of the decade, if I try 1991, since it is not the first year of 1990, it will return nil for this optional.  To safely use init?(rawValue: Int), you can use Optional Binding:</p>
<pre class="lang:swift decode:true">if let otherDecade = FirstYearOfDecade(rawValue: 1990) {
    switch otherDecade {
    case .Nineties:
        print("I love the 90s")
    default:
        print("What decade are you talking about?")
    }
} else {
    print("Couldn't find it")
}</pre>
<p>&nbsp;</p>
<h2>Conclusion</h2>
<p>Those are the basics to using enumerations in Swift.  I did mention earlier that they are much more similar to classes in Swift than they were in C or Objective-C.  This allows them to also have methods, properties (besides the associated values), and more.  For now though, I just wanted to cover what makes enumerations different, as opposed to how it is similar to its relatives.  You can read more about classes in the post <a title="Classes In Swift — An Introduction" href="http://www.codingexplorer.com/classes-in-swift-an-introduction/">Classes In Swift — An Introduction</a>, and structures in the post <a title="Structures in Swift" href="http://www.codingexplorer.com/structures-swift/">Structures in Swift</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftEnumerations">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Loops, Switch Statements, and Ranges in Swift</title>
		<link>https://www.codingexplorer.com/loops-switch-statements-ranges-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 30 Jul 2014 19:33:16 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=347</guid>

					<description><![CDATA[<p>I&#8217;m going to go a bit old school on this one.  We&#8217;re staying on Swift here, don&#8217;t worry, but I want to cover something that has been around since the early days of C.  They were probably earlier, but that&#8217;s the oldest language besides BASIC that I personally have experience with.  We&#8217;re going to talk [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/loops-switch-statements-ranges-swift/">Loops, Switch Statements, and Ranges in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I&#8217;m going to go a bit old school on this one.  We&#8217;re staying on Swift here, don&#8217;t worry, but I want to cover something that has been around since the early days of C.  They were probably earlier, but that&#8217;s the oldest language besides BASIC that I personally have experience with.  We&#8217;re going to talk about some classic control flow and how Swift has updated them&#8230; or kept them the same, we&#8217;ll see.<br />
<span id="more-347"></span></p>
<h2>Standard For Loop</h2>
<h2>For-In Loop</h2>
<p>When I learned about the equivalent in C#, I used these as often as I could.  If I didn&#8217;t need to know the index for something, it was amazing.  It basically lets you step through a range or collection and store whatever is at that index in a temporary variable that you can use in that loop iteration.  So if we had an array and wanted to step through it:</p>
<pre class="lang:swift decode:true">let primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

for number in primeNumbers {
    print("\(number)")
}</pre>
<p>That will just step through each number and print them out on a new line.  It is quite simple.</p>
<h3>For-In Loop with Ranges</h3>
<p>It also works with ranges, and they have their own interesting new syntax.  Ranges basically give you a shorthand for writing a series of numbers.  The are pretty useful in for loops (shorter than a normal for loop, with less semicolons), but even better with <a href="#SwitchStatements">Switch Statements</a></p>
<p>You have 2 Range Operators, closed and half-open.</p>
<ul>
<li>Closed Range Operator &#8221; &#8230; &#8221; &#8211; makes a range including the last number, so &#8221; 0&#8230;3 &#8221; is a range containing 0, 1, 2, and 3.</li>
<li>Half-Open Range Operator &#8221; ..&lt; &#8221; &#8211; makes a range excluding the last number, so &#8221; 0 ..&lt; 3 &#8221; is a range containing 0, 1, and 2.</li>
</ul>
<p>Half-Open used to have another operator, but I definitely like this one better.  It basically is saying it is a range operator (with the &#8220;..&#8221;), but less than (with the &#8220;&lt;&#8220;) the last number, like you would in many standard for loops.  As such, to do an equivalent of our normal for loop from the first section, we would do this:</p>
<pre class="lang:swift decode:true">for index in 0..&lt;3 {
    print(index)
}</pre>
<p>Since we used a half-open range, it steps through 0, 1, and 2.</p>
<h2>If Statement</h2>
<p>Much like the standard for loop, hasn&#8217;t changed much.  There are two notable differences from C though.  While I&#8217;m not certain if parentheses around the if-statement&#8217;s conditional were REQUIRED in C, the are most definitely not in Swift.  In C though, the brackets surrounding the if-statement&#8217;s code block (what to execute if that condition is met) were not required.  If you only needed 1 line of code to run, you could just say that, and use the indentation to make it more obvious to the reader.  Thankfully though, the Swift team seems to agree with me that those curly-braces should be required for if-statement code blocks.</p>
<p>So just to be clear, in Swift, parentheses around the conditional are optional, but curly-braces around the code block are required.  Other than those differences (which always good style in C anyway), the statement is pretty much the same, for example:</p>
<pre class="lang:swift decode:true">if someNumber &gt; 0 {
    print("That is a positive number")
} else if someNumber &lt; 0 {
    print("That is a negative number")
} else {
    print("That number is zero")
}</pre>
<p><a name="SwitchStatements"></a></p>
<h2>Switch Statement</h2>
<p>Unlike if statements, switch statements have had quite the update in Swift.  The general syntax is very similar, but there are a few major differences, they are:</p>
<ul>
<li>Swift switch statements do not implicitly fall-through — In C, you had to use the keyword <strong>break</strong> to stop as you were done in each case.  In Swift, the compiler knows that if it sees the next case statement, the one you are on has completed executing.</li>
<li>Swift switch statements can match multiple cases on the same line — In Swift, you separate each value by a comma before the colon.  In C, you could abuse the fall-through to do something similar here, but you would have a series of &#8220;case blah:&#8221; &#8220;case blah2:&#8221; listed, that just looks messy.</li>
<li>Swift switch statements can match against ranges — Remember those ranges that I mentioned in the for-in section?  They work here too, which is even cleaner than the multiple cases separated by commas mentioned above, if you have numeric values.</li>
<li>Swift switch statements can have more complex cases via pattern matching — This is particularly useful when dealing with enumerations.  Enumerations can have values associated with different enumeration cases, and you can bind those to variables here, or even have sub-cases dealing with that associated value.  There is a lot to this aspect of switch statements, and also for enumerations.  Both will be covered by future posts (Enumerations are covered in the future post <a title="Enumerations in Swift" href="http://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a>), but I wanted to mention it for the introduction to switch statements in Swift.</li>
</ul>
<p>Switch statements in Swift must be exhaustive.  They must contain all possible cases, otherwise the compiler will give an error.  Of course you can use a default case so you don&#8217;t actually have to write each case all yourself if there are ones you really don&#8217;t care about, but it must be exhaustive, one way or another.</p>
<p>Other than the lack of requiring<strong> break</strong>, the switch statement actually looks pretty much the same as it did before.  Even these new capabilities are done in ways that really look like they fit in with the old style and are just slight extensions to it (like comma separated case values).</p>
<p>Here&#8217;s a standard switch statement:</p>
<pre class="lang:swift decode:true">switch aNumber {
case 1:
    print("uno")
case 2:
    print("dos")
case 3:
    print("tres")
default:
    print("Something else")
}</pre>
<p>Here is a multiple value per case switch statement:</p>
<pre class="lang:swift decode:true">switch aNumber {
case 0,2,4,6,8,10:
    print("This is an even number between 0 and 10")
case 1, 3, 5, 7, 9:
    print("This is an odd number between 0 and 10")
default:
    print("This number is not between 0 and 10")
}</pre>
<p>Here is a switch statement matching against ranges:</p>
<pre class="lang:swift decode:true">switch aNumber {
case 0...5:
    print("This number is between 0 and 5")
case 6...10:
    print("This number is between 6 and 10")
default:
    print("This number is not between 0 and 10")
}</pre>
<p>As I said earlier, there is a lot to talk about in relation to pattern matching in switch statements, so instead of trying to squeeze it into an already long post, it will have its own post to explain that capability, <a href="http://www.codingexplorer.com/pattern-matching-in-swift/">Pattern Matching in Swift</a>.</p>
<h2>While and Repeat-While Loops</h2>
<p>I will squeeze this in though.  Much like the if statement, they did not change much.  The only difference is that they do not need parenthesis around the conditional.</p>
<pre class="lang:swift decode:true">while i &lt; 5 {
    print("\(i)")
    i += 1
}</pre>
<p>Below is an example of a Repeat-While loop (formerly known as the Do-While loop):</p>
<pre class="lang:swift decode:true">var someOptionalInt: Int? = nil

repeat {
    print("Trying to get an integer")
    someOptionalInt = functionThatMayReturnAnInteger()
    
} while (someOptionalInt != nil)

print("Got a nil instead")</pre>
<p>As you see, here it tries to fill the &#8220;someOptionalInt&#8221; variable, and if it does, it keeps going.  If it doesn&#8217;t, it will break out of the loop and tell the user that it got a nil instead.  In this example, someOptionalInt started as nil, and it still went into the loop to try.  Now, to do anything USEFUL safely with this value, you would have to test if it is nil inside the loop if you don&#8217;t want it to crash when trying to unwrap someOptionalInt.  While that does mean you have to test twice, it also means that you only need to call your functionThatMayReturnAnInteger() function inside your loop.  Otherwise, you would have to run it outside of the loop once, and then have to write it inside the loop again.  I&#8217;m not the biggest fan of repeat-while loops, but they have their place.</p>
<p>Below is a quote from <a title="language agnostic - Test loops at the top or bottom? (while vs. do while) - Stack Overflow" href="http://stackoverflow.com/a/224075/2775523">Stack Overflow</a> (reformatted and slightly paraphrased) that sums up when you would use one or the other quite nicely:</p>
<ul>
<li>If it should run zero or more times, test at the beginning (While Loop)</li>
<li>If it must run once or more, test at the end (Repeat-While Loop)</li>
</ul>
<h2>Conclusion</h2>
<p>So, for a quick summary of the changes (or lack thereof):</p>
<p>Minor changes:</p>
<ul>
<li>If Statement &#8211; Same except no longer requires parenthesis around conditional, and curly-braces around code block are required.</li>
<li>While or Repeat-While Loop &#8211; Same except no longer requires parenthesis around conditional.</li>
</ul>
<p>Major changes:</p>
<ul>
<li>For-in Loop added &#8211; Step through each value in a collection or range and assign to a temporary variable to do work.</li>
<li>Switch Statement &#8211; No more implicit fall-through,  can match against multiple cases on same line, ranges, and patterns.</li>
</ul>
<p>See my future post <a title="Enumerations in Swift" href="http://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a> for more information.</p>
<p>Check out this future post about <a href="http://www.codingexplorer.com/pattern-matching-in-swift/">Pattern Matching in Swift</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftLoopsSwitchStatements">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/loops-switch-statements-ranges-swift/">Loops, Switch Statements, and Ranges in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Functions in Swift: Parameters and Return Types</title>
		<link>https://www.codingexplorer.com/functions-swift-parameters-return-types/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 28 Jul 2014 19:15:09 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=335</guid>

					<description><![CDATA[<p>I think we&#8217;ve gone over the basics of variables in Swift enough.  It is time to talk about functions in Swift.  Now, we have talked about these to some extent before, and I took it as a given that people would understand a bit.  But now I think it is time to actually start diving [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/functions-swift-parameters-return-types/">Functions in Swift: Parameters and Return Types</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I think we&#8217;ve gone over the basics of variables in Swift enough.  It is time to talk about functions in Swift.  Now, we have talked about these to some extent before, and I took it as a given that people would understand a bit.  But now I think it is time to actually start diving in and explaining more specifics.</p>
<p>Functions are blocks of code that perform a task.  You can then call these functions at different places, which makes fixing bugs much easier than the alternative.  If you just copied and pasted the code everywhere, and you found a bug, you would have to change each one to fix that bug.  With functions, you just change it one place, and everything that calls it gets the new fixed version of that block of code.  The entire app itself is wrapped within a function called &#8220;main&#8221;, but you don&#8217;t normally interact with it, unless there&#8217;s a crash.  Functions usually take arguments, and very often return data back to where it was called from.<br />
<span id="more-335"></span></p>
<h2>Vocabulary Lesson</h2>
<p>There are a few words that I&#8217;ll use here that it may be best to have defined outright, so here goes:</p>
<ul>
<li>Function Signature (aka Signature):  The top line of the function, outside of that function&#8217;s curly braces.  This describes the inputs, return type, and visibility of a function.</li>
<li>Parameters:  The inputs to a function.  These are the variables created in the function signature, for use inside the function to do its job.</li>
<li>Arguments:  Where the parameters come from.  When you call a function, and give it the appropriate inputs, these are called arguments.</li>
<li><a title="Arity | Define Arity at Dictionary.com" href="http://dictionary.reference.com/browse/arity">Arity</a>:  The number of arguments a function takes.</li>
</ul>
<h2>Function parameters</h2>
<p>Functions take in data to do their job, usually.  There are situations where they don&#8217;t, such as to return a random number, or maybe play a sound, or maybe to access something from a global variable, but in general, they take inputs.  Functions in Swift can take many different numbers of parameters including zero, one, multiple, or even an unknown number of them (that one is called a Variadic parameter).  The current article on Wikipedia about <a title="Variadic function - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Variadic_function">Variadic Functions</a> says that they are functions of indefinite arity.  I had never heard of that word before today.</p>
<p>For these examples, I am going to show functions with no return types, just to make the syntax simpler to just demonstrate differences in function parameters.  If you want to read about return types, skip ahead to the <a href="#returnTypes">Return Types for Functions</a> section.</p>
<h3>No Parameters</h3>
<p>Like I had mentioned, this could be used as something to generate something randomly or do some sort of side effect like toggle something or play a sound.  These are the simplest ones.  A no parameter function would look like this:</p>
<pre class="lang:swift decode:true">func playBeepNoise()</pre>
<p>Very simple, it takes no parameters, and no arguments.  Inside of this one, you would probably pass some audio file to a media player or whatnot and just have it play.</p>
<h3>One Parameter with No External Name</h3>
<p>If you want multiple parameters with no external name, you must use the &#8221; _ &#8221; underscore character as the external name, which is the first label listed for that argument:</p>
<pre class="lang:swift decode:true">func playSpecificBeepNoiseWithDelayOf(_ aNumber: Int, _ filename: String)</pre>
<h3>Variadic Parameters &#8211; Unspecified number of parameters</h3>
<p>These are interesting.  You can actually create a method that works on any number of parameters, well, any number of the same type.  Basically, it will create an array of the values you put in, then you can iterate through them and do whatever you want.  You could have a method that sums all the numbers sent into it, or maybe one that puts a bunch of strings together joined by spaces.  Basically, you say a value, give it its type, and then add three period characters afterwards to make it a variadic parameter.  For example:</p>
<pre class="lang:swift decode:true">func printStringsJoinedWithSpaceAfterEach(words: String...) {
    var result = ""
    for word in words {
        result += word
        result += " "
    }
    
    print(result)
}</pre>
<p>You would call it like this:</p>
<pre class="lang:swift decode:true">printStringsJoinedWithSpaceAfterEach(words: "These", "are", "multiple", "words")
//Console Output: "These are multiple words "</pre>
<p>Whether that exact function is a good idea is inconsequential (and yes, I know there is an extra space at the end), it nonetheless takes as many parameters as you want.</p>
<p>You can have more than just the Variadic parameter in your function prototype<del>, but the variadic parameter must be the last one listed</del>.  From Swift 2 onwards, a Variadic parameter can be in any position in the function signature.  Prior to it, it could only be put at the end, so now:</p>
<pre class="lang:default decode:true">func printStringsJoinedWithSpaceAfterEach(aNumber: Int, words: String...)  //Is Valid

func printStringsJoinedWithSpaceAfterEach(words: String..., aNumber: Int)  //Is Also Valid (Since Swift 2)</pre>
<p>You also can only have one variadic parameter per function.  Apple&#8217;s iBook explicitly states that you can only use one variadic parameter per function.<br />
<a name="namingParameters"></a></p>
<h2>Naming Parameters</h2>
<p>It is common in Objective-C to name each of your parameters.  While I started showing you how to do it without having to type them when calling, it is often a good idea to have them as part of your call to this function.  It makes the code much more understandable (but longer), since you know what each parameter is without having to look up the function.  There are two ways to do this.</p>
<h3>Use a different External Name</h3>
<p>If you want a more descriptive name when calling it, but a shorter name to use internally, you just write the external name before the internal name, like so:</p>
<pre class="lang:swift decode:true">func playBeepNoise(withDelayInMilliseconds msDelay: Int) {
    print(String(msDelay))
}

//Called like this
playBeepNoise(withDelayInMilliseconds: 42)</pre>
<p><a name="returnTypes"></a></p>
<h2>Return Types for Functions</h2>
<p>Like function parameters, you can return different amounts.  We&#8217;ve already seen functions with no return type.  Additionally, a function can return one, multiple (known number though, no variadic return types, an array is the closest you get).  The multiple return value is called a &#8220;tuple&#8221;.  According to <a title="Tuple | Define Tuple at Dictionary.com" href="http://dictionary.reference.com/browse/tuple">Dictionary.com</a>, both pronunciations of it are valid (too-pull and tuh-pull).  Some people suggest that it should be &#8220;tuh-pull&#8221;, since it is related to words like &#8220;quintuple&#8221; or &#8220;octuple.&#8221;  I personally like saying &#8220;too-pull&#8221; myself, but that&#8217;s just me.</p>
<p>You can read more about tuples in the post <a title="Tuples in Swift: Create, Read, and Return" href="http://www.codingexplorer.com/tuples-in-swift-create-read-and-return/">Tuples in Swift: Create, Read, and Return</a>.</p>
<h3>Single Return Type</h3>
<p>Most programming languages only have one return type, if any.  As such, of course it is possible to do so in Swift.  I have not personally seen it written like it is in Swift elsewhere, but simple nonetheless:</p>
<pre class="lang:swift decode:true">func addFiveToThisNumber(number: Int) -&gt; Int</pre>
<p>You just make that arrow character, which is just a hyphen and a greater-than symbol, and then follow it with the type name.</p>
<h3>Multiple Return Types</h3>
<p>It sounds like it should be complex, but they really set it up similar to how you set parameters, just on the return type side, so you basically enclose your return types in parenthesis and give each a name and type separated by a comma after that arrow ( -&gt; ), such as:</p>
<pre class="lang:swift decode:true">func addAndSubtractTen(from number: Int) -&gt; (small: Int, large: Int) {
    let smallResult = (number - 10)
    let largeResult = (number + 10)
    
    return (smallResult, largeResult)
}</pre>
<p>As you can see, you just return it between parenthesis.  You would then use it like this:</p>
<pre class="lang:swift decode:true">let answer = addAndSubtractTen(from: 24)

answer.small
answer.large</pre>
<h3>Optional Multiple Return Types</h3>
<p>You could also make the whole tuple optional by simply putting a question mark at the end of the return type, like so:</p>
<pre class="lang:swift decode:true">func giveTwoValuesIfValid(input: Int) -&gt; (one: Int, two: Int)?</pre>
<p>You would just return nil, instead of something in parenthesis like you normally would when returning a tuple.</p>
<h2>Conclusion</h2>
<p>Since functions are so important to programming, they definitely need a lot of flexibility to do their job well.  Swift has given more flexibility than most languages by letting functions return tuples.  This post may be a bit Comp Sci 101, but by doing the research for this I even learned more, like how to write variadic parameters.  I also learned the word &#8220;arity,&#8221; so there are some nuggets of new things hidden amongst the introductory information.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftFunctionsParamReturn">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/functions-swift-parameters-return-types/">Functions in Swift: Parameters and Return Types</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>PregTracker 1.0.1 Released!</title>
		<link>https://www.codingexplorer.com/pregtracker-1-0-released/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 26 Jul 2014 06:58:25 +0000</pubDate>
				<category><![CDATA[My Apps]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=258</guid>

					<description><![CDATA[<p>I did not really mention it much online, but my wife became pregnant in the fall of 2013.  Every time somebody would ask me &#8220;how far along is she?&#8221;  I would have to stop and think, do some mental math, and eventually tell them the answer.  I figured there had to be a better way. Why [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/pregtracker-1-0-released/">PregTracker 1.0.1 Released!</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I did not really mention it much online, but my wife became pregnant in the fall of 2013.  Every time somebody would ask me &#8220;how far along is she?&#8221;  I would have to stop and think, do some mental math, and eventually tell them the answer.  I figured there had to be a better way.</p>
<p><span id="more-258"></span></p>
<h2>Why I Wrote PregTracker</h2>
<p>At the time, I was working on another app, that had to do with shopping lists (yes, very similar to a to-do list, but not quite!).  It was using Core Data, which I must say, is not the best thing to start with when you are just getting your feet wet in iOS.  It was going pretty decently nonetheless, but I digress.</p>
<p>I wanted something much easier to do, to really be able to learn programming for iOS, instead of fighting with advanced topics like Core Data right out of the gate.  I figured a pregnancy tracker app was perfect.  It&#8217;s function is very simple, but it will still give me a chance to learn many aspects of programming for iOS, without nearly as much pressure.</p>
<p>There are many other fine apps that help you track your pregnancy.  They all have a lot more features than mine, but at least at this point, that is actually one of the major motivations.  Yes the pictures are helpful, and a lot of text about week by week differences about your baby are good, but I wanted a simple app.</p>
<p>I wanted one that should just enough information right on the front page, in a simple and easy to read format.</p>
<p>After you&#8217;ve set a due date, every other time you open the app you are greeted with this:</p>
<div id="attachment_288" style="width: 185px" class="wp-caption aligncenter"><a href="http://www.codingexplorer.com/wp-content/uploads/2014/07/iPhone4inch-Progress.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-288" class="wp-image-288 size-medium" src="http://www.codingexplorer.com/wp-content/uploads/2014/07/iPhone4inch-Progress-175x300.png" alt="Main Progress Screen for PregTracker 1.0.1" width="175" height="300" srcset="https://www.codingexplorer.com/wp-content/uploads/2014/07/iPhone4inch-Progress-175x300.png 175w, https://www.codingexplorer.com/wp-content/uploads/2014/07/iPhone4inch-Progress-597x1024.png 597w, https://www.codingexplorer.com/wp-content/uploads/2014/07/iPhone4inch-Progress.png 640w" sizes="auto, (max-width: 175px) 100vw, 175px" /></a><p id="caption-attachment-288" class="wp-caption-text">Main Progress Screen for PregTracker 1.0.1</p></div>
<p>&nbsp;</p>
<p>A very simple, clean interface.  You can clearly see your due date, text saying exactly how far along you are, a circular progress bar, and text saying what trimester your pregnancy is.  I think it fits very well with the theme of iOS7 (which it was being programmed for originally), and it gives just what I wanted, right on the first screen.</p>
<h2>The App and this Blog</h2>
<p>It took some time to finish, especially with it being my first app, but I think that was probably good.  I got to use it through the duration of the entire pregnancy, and really see how people will interact with the app over a long period of time helped me work out several bugs, especially with <a title="Updating an app when returning from background in iOS" href="http://www.codingexplorer.com/updating-an-app-when-returning-from-background-in-ios/">Updating an app when returning from background in iOS</a> and <a title="Using UILocalNotification" href="http://www.codingexplorer.com/using-uilocalnotification/">Using UILocalNotification</a>.  I submitted it to Apple about a week after my son&#8217;s original due date, and got it on the App Store on July 1, 2014.</p>
<p>I did not announce my app on this website yet, so jumping straight to version 1.0.1 might be a bit odd, but there were a few bugs I found after approval that I wanted to fix before really trying to push the app.  It did have its own website, or at least a page on my separate apps website.  The astute among you may have noticed the new &#8220;Apps&#8221; button in the top menu, which would link to my apps subdomain <a title="Coding Explorer Apps — Apps Written by the Coding Explorer" href="http://apps.codingexplorer.com/">Coding Explorer Apps</a>.  That showed up on this page with no fanfare, but I knew I had to connect to it.  I wanted to get a few more Swift articles under my belt before self-promotion, and fix those few bugs I mentioned a moment ago as well.</p>
<p>Working on this app gave me most of the non-Swift topics I talked about on this blog, these include, but are not limited to:</p>
<ul>
<li><a title="Supporting Dynamic Type for iOS7 Apps" href="http://www.codingexplorer.com/supporting-dynamic-type-for-ios7-apps/">Supporting Dynamic Type for iOS7 Apps</a></li>
<li><a title="Updating an app when returning from background in iOS" href="http://www.codingexplorer.com/updating-an-app-when-returning-from-background-in-ios/">Updating an app when returning from background in iOS</a></li>
<li><a title="Storing data with NSUserDefaults" href="http://www.codingexplorer.com/storing-data-with-nsuserdefaults/">Storing data with NSUserDefaults</a></li>
<li><a title="Displaying a human readable NSDate" href="http://www.codingexplorer.com/displaying-a-human-readable-nsdate/">Displaying a human readable NSDate</a></li>
<li><a title="Introduction to UIColor" href="http://www.codingexplorer.com/introduction-to-uicolor/">Introduction to UIColor</a></li>
<li><a title="Using UILocalNotification" href="http://www.codingexplorer.com/using-uilocalnotification/">Using UILocalNotification</a></li>
<li><a title="Add sharing to your app via UIActivityViewController" href="http://www.codingexplorer.com/add-sharing-to-your-app-via-uiactivityviewcontroller/">Add sharing to your app via UIActivityViewController</a></li>
<li><a title="Getting Started With NSNumberFormatter" href="http://www.codingexplorer.com/getting-started-with-nsnumberformatter/">Getting Started With NSNumberFormatter</a></li>
<li><a title="Getting started with NSNotificationCenter" href="http://www.codingexplorer.com/getting-started-with-nsnotificationcenter/">Getting started with NSNotificationCenter</a></li>
<li><a title="Replace Keyboard with UIDatePicker" href="http://www.codingexplorer.com/replace-keyboard-with-uidatepicker/">Replace Keyboard with UIDatePicker</a></li>
<li><a title="MFMailComposeViewController – Send email in your apps" href="http://www.codingexplorer.com/mfmailcomposeviewcontroller-send-email-in-your-apps/">MFMailComposeViewController – Send email in your apps</a></li>
</ul>
<h2>Acknowledgements</h2>
<p>I want to particularly acknowledge a few resources I used in the creation of this app.</p>
<p>Firstly, you see that snazzy circular progress bar on the main page?  I knew I wanted a circular progress bar, but I did not know how to make one, and that was one of the first things I knew I wanted in this app.  I got that from Joe Conway of Stable/Kernel, available at <a title="iOS Circular Progress Bar | stable/kernel Blog" href="http://stablekernel.com/blog/ios-circular-progress-bar/">http://stablekernel.com/blog/ios-circular-progress-bar/</a> .  I could have used a standard progress bar, but I felt this made more sense, especially as a primary part of the user interface.</p>
<p>Secondly, I can&#8217;t draw very well, and do not currently have the budget for a designer.  So I was very glad when I found the free Tab Bar icons courtesy of PixEden.com, available at <a title="Premium and Free Media Icons Set | Pixeden" href="http://www.pixeden.com/media-icons">http://www.pixeden.com/media-icons</a> .  They provided the timeline and settings tab bar icons.  I actually found this website via <a title="The iOS 7 Design Cheat Sheet - Ivo Mynttinen / User Interface Designer" href="http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/">The iOS Design Cheat Sheet</a>, created by <a title="Ivo Mynttinen (ivomynttinen) on Twitter" href="https://twitter.com/ivomynttinen">Ivo Mynttinen</a>.</p>
<p>Thirdly, while not particularly programming related, I wanted to thank one source of the data I used in this app.  I was also curious about what milestones or length&#8217;s my baby probably was at different times, so I added those to the app as well in that timeline tab.  I got the average length information from BabyCenter, L.L.C., available at <a title="Average fetal length and weight chart | BabyCenter" href="http://www.babycenter.com/average-fetal-length-weight-chart">http://www.babycenter.com/average-fetal-length-weight-chart</a> .  Having all of this information in a cohesive and easy to read format was very helpful in making that part of the app.</p>
<p>Finally, this particular resource has been a big help in me learning to program in iOS since the beginning.  The great classes taught at Stanford about programming for iOS by Paul Hegarty, available on iTunes U at <a title="Developing iOS 7 Apps for iPhone and iPad - Download Free Content from Stanford on iTunes" href="https://itunes.apple.com/us/course/developing-ios-7-apps-for/id733644550">https://itunes.apple.com/us/course/developing-ios-7-apps-for/id733644550</a> .  Watching these iTunes U videos, as well as the associated lecture note PDFs have been extremely helpful.</p>
<h2>Future of the App</h2>
<p>So what plans do I have for this app?  Well, one thing common in many other apps of this type is the comparison of your baby&#8217;s size to familiar objects to give you a sense of scale.  I have been thinking of adding that, and maybe more information about what is going on that week with the user&#8217;s baby.  Though if I do that, I will want to keep it a bit tucked away to not clutter the UI.  Many other apps have it directly on the main screen, and while it is good to have, I want the main screen to still be very clear about how many weeks along your baby is.</p>
<p>One thing in particular though, I think it really lends itself well to a Today Extension (aka Notification Center Widget) for iOS 8.  Currently it uses the app icon badge to also show the user how far along the baby is so they don&#8217;t have to even open the app.  A Today Extension is a more appropriate place to show this information, and I can write a bit more in it than just the weeks along, like on the app icon badge.  So when I write about Today Extensions on this blog, you&#8217;ll know that this is probably what I&#8217;m working on.</p>
<h2>Conclusion</h2>
<p>I know this isn&#8217;t really a programming post, but its my first app, I wanted to be able to announce it to those that are learning alongside me.  I&#8217;m not sure how often I&#8217;ll post about my own apps directly like this, but probably only for major versions, or new apps.</p>
<p>I am working on a followup app, taking place where this one leaves off about baby development after they are born.  This one I am writing in Swift, so after the more introduction to Swift posts that I&#8217;m doing now (with <a title="Swift Variables and Constants" href="http://www.codingexplorer.com/swift-variables/">variables</a>, <a title="Swift Optionals – Declaration, Unwrapping, and Binding" href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">optio</a><a title="Optional Chaining and Implicitly Unwrapped Optionals in Swift" href="http://www.codingexplorer.com/optional-chaining-implicitly-unwrapped-optionals-swift/">nals</a>, functions (on their way)), look to see more posts about how I handle some new (to me) concept in Swift while working on my new app.</p>
<p>Thank you for reading this post, and if you know anybody having a child soon, please don&#8217;t hesitate to share this app with them.  I hope this app will be as helpful to others as it was to me.  If any of you check out the app, and are curious how I implemented something, don&#8217;t hesitate to ask.  As usual, I can be reached on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>.  Thanks!</p>
<hr />
<p>&nbsp;</p>
<p style="text-align: center;">Available on the <a title="PregTracker on the App Store on iTunes" href="https://itunes.apple.com/us/app/pregtracker/id892542016?mt=8&amp;at=10lJ3x&amp;ct=blog-pregTracker1_0_1Released">App Store</a> for the iPhone and iPad for only $0.99</p>
<p><a title="PregTracker on the App Store on iTunes" href="https://itunes.apple.com/us/app/pregtracker/id892542016?mt=8&amp;at=10lJ3x&amp;ct=blog-pregTracker1_0_1Released"><img loading="lazy" decoding="async" class="aligncenter wp-image-324 size-thumbnail" src="http://www.codingexplorer.com/wp-content/uploads/2014/07/pregTrackerRounded-150x150.png" alt="pregTrackerRounded" width="150" height="150" srcset="https://www.codingexplorer.com/wp-content/uploads/2014/07/pregTrackerRounded-150x150.png 150w, https://www.codingexplorer.com/wp-content/uploads/2014/07/pregTrackerRounded-300x300.png 300w, https://www.codingexplorer.com/wp-content/uploads/2014/07/pregTrackerRounded.png 960w" sizes="auto, (max-width: 150px) 100vw, 150px" /></a></p>
<p><a href="https://itunes.apple.com/us/app/pregtracker/id892542016?mt=8&amp;at=10lJ3x&amp;ct=blog-pregTracker1_0_1Released"><img loading="lazy" decoding="async" class="aligncenter" style="border: 0;" src="https://linkmaker.itunes.apple.com/htmlResources/assets//images/web/linkmaker/badge_appstore-lrg.png" alt="iTunes" width="135" height="40" hspace="40" vspace="40" /></a></p>
<p>The post <a href="https://www.codingexplorer.com/pregtracker-1-0-released/">PregTracker 1.0.1 Released!</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Access Control in Swift</title>
		<link>https://www.codingexplorer.com/access-control-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 24 Jul 2014 06:15:37 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[Access Controls]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=293</guid>

					<description><![CDATA[<p>The access control in Swift is much more like the access control I am accustomed to in other languages like C# or Java, and I am quite thankful for that.  I&#8217;m not saying there is anything wrong with Objective-C&#8217;s way of doing it, while it was different, I did like having the private properties in [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/access-control-swift/">Access Control in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The access control in Swift is much more like the access control I am accustomed to in other languages like C# or Java, and I am quite thankful for that.  I&#8217;m not saying there is anything wrong with Objective-C&#8217;s way of doing it, while it was different, I did like having the private properties in the interface block of the implementation (.m) file, and the public properties and methods in the header (.h) file.  It made it easy to know exactly where to look.</p>
<p>Nonetheless, access control is here in Swift, so here we go.  You can set access control to many things in Swift, particularly properties and methods, but you can even set it to types, initializers, subscripts, or protocols.  Swift currently has three levels of access control:</p>
<ul>
<li>Public</li>
<li>Internal</li>
<li>Fileprivate</li>
<li>Private</li>
</ul>
<p><span id="more-293"></span></p>
<p>The section in Apple&#8217;s iBook <a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftAccessControl" target="itunes_store" rel="noopener noreferrer">The Swift Programming Language</a>, described the major differences between them in a few paragraphs, when writing this, I kept having to look back to remember the specific aspects of where they were all visible.  So, I thought it would be better to show the major differences in tabular form&#8230;. behold:</p>
<p>&nbsp;</p>
<table style="height: 100px; width: 450px;" border="1" width="450">
<tbody>
<tr>
<td>Visible to&#8230;</td>
<td style="text-align: center;">Defining Scope</td>
<td style="text-align: center;">Defining Source</td>
<td style="text-align: center;">Defining Module</td>
<td>
<p style="text-align: center;">Source that Imports</p>
<p style="text-align: center;">Defining Module</p>
</td>
</tr>
<tr>
<td>Public</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;">✓</td>
</tr>
<tr>
<td>Internal</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;"></td>
</tr>
<tr>
<td>Fileprivate</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
</tr>
<tr>
<td>Private</td>
<td style="text-align: center;">✓</td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
</tr>
</tbody>
</table>
<p>Now, we haven&#8217;t talked about Module&#8217;s yet on this blog, but basically, this is Swift&#8217;s name for &#8220;namespaces&#8221; in other languages.  They are also part of how Apple makes headers unnecessary in Swift.  Effectively, a module is basically the target you are building for.  For most of us, that means &#8220;your app,&#8221; but it could also be a framework instead.</p>
<p>Let&#8217;s look a little more in depth into these access control levels.</p>
<h2>Swift Access Controls</h2>
<h3>Public</h3>
<p>As expected, public is the most visible access control level you can have.  It allows the user to use that property, function, etc in the defining source, the module that source is in, and anything that imports that module.  Basically, it can be seen anywhere.  This is particularly important for frameworks.  This is what will give your framework a public API, to be called by whatever imports your framework.</p>
<h3>Internal</h3>
<p>This is the default access level.  It can be seen in the defining source, as well as the module that source is in, but it cannot be seen by something that imports that module.  If used in a framework, it lets other parts of your module see these aspects, but not something that imports your module.  In Objective-C, it would basically be equivalent to having them declared in your header file.</p>
<h3>Fileprivate</h3>
<p>Fileprivate can only be seen in the defining source.  This hides the implementation details of that source file, so that the rest of your module does not have access to parts that have little meaning outside of the context of the original source file.  In Objective-C, it would be equivalent to being declared in the interface part of your implementation file.</p>
<h3>Private</h3>
<p>This is the least visible access control level.  Private can only be seen in the defining scope.  So if you made an extension of your class in the same source file, but wanted a function only visible in that extension and not in the main class, you would declare it private.</p>
<h2>The @testable Attribute<del></del></h2>
<p>Since the release of Swift 2, these issues have been mitigated with the addition of the &#8221; @testable &#8221; import attribute.  It basically treats anything that is marked as &#8220;internal&#8221; as if it were public, to the code that imports using that attribute.  So to test with your internal methods, properties, types, etc., in your unit test class, just &#8220;@testable&#8221; before the import of whichever module you are testing.</p>
<h2>Using Access Controls</h2>
<p>With all this talk about access controls, I should probably show how they are used?  Well, they are really simple, you basically just begin your declaration of a variable or class with the access modifier you want, so:</p>
<pre class="lang:swift decode:true">public class myPublicTranslator { }

public func translateSomeText(inputText: String) -&gt; String { }

fileprivate let implementationDetail = "A Secret"

private let superSecretImplementationDetail = "A SUPER Secret"</pre>
<p>Nothing too special there.</p>
<h2>Limitations to Access Controls</h2>
<p>There are a few limitations to access controls, and most of them are just to enforce common sense.  For instance, a public variable cannot have an internal or private type.  That seems pretty obvious.  If the type was private, how could anything that can only read the public variable have access to it?</p>
<p>Another similarly obvious one, a function can have an access level no more visible than the least visible type in its parameters or return value.  You can make a private type that contains public and internal types as parameter or return types.  However, you cannot make a public function that uses internal parameter or return types.  Similar reasoning, since nothing from another module that can only read public items could possibly have access to internal or private types.</p>
<h2>Conclusion</h2>
<p>Access controls are definitely a welcome addition to Swift.  They will make it much easier to enforce interfaces between your source files and modules, as opposed to just leaving your implementation details out for all to see.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftAccessControl" target="itunes_store" rel="noopener noreferrer">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/access-control-swift/">Access Control in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Optional Chaining and Implicitly Unwrapped Optionals in Swift</title>
		<link>https://www.codingexplorer.com/optional-chaining-implicitly-unwrapped-optionals-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 21 Jul 2014 23:00:36 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=272</guid>

					<description><![CDATA[<p>As promised last time, here is part two of my post about Swift optionals.  Here we will discuss a few more advanced aspects on how to deal with optionals, optional chaining and implicitly unwrapped optionals.  These are a few more tricks to get values out of optionals, while keeping Swift code much cleaner than its predecessors.  Optional [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/optional-chaining-implicitly-unwrapped-optionals-swift/">Optional Chaining and Implicitly Unwrapped Optionals in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As promised last time, here is part two of my post about Swift optionals.  Here we will discuss a few more advanced aspects on how to deal with optionals, optional chaining and implicitly unwrapped optionals.  These are a few more tricks to get values out of optionals, while keeping Swift code much cleaner than its predecessors.  Optional chaining makes it easy to drill into multiple levels of optional values.  Implicitly unwrapped optionals, while not as safe as normal optionals, are often used under the assumption that the value that it is describing is never, or usually not, nil.</p>
<p><span id="more-272"></span></p>
<h2>Optional Chaining</h2>
<p>What if we had to use a class optionally, and that class in turn has something optional inside it?  You could use a series of &#8220;<span style="color: #bb2ca2;">if let</span>&#8221; checks to go into it to grab it, but Apple decided to make this easier and with less code by using optional chaining.  You still have to use &#8220;<span style="color: #bb2ca2;">if let</span>&#8221; when performing optional chaining, but it lets you multiple levels deep with only 1 &#8220;<span style="color: #bb2ca2;">if let</span>&#8220;.  Let&#8217;s look at this class involving a person, their pet, and the pet&#8217;s favorite toy.</p>
<pre class="lang:swift decode:true">class Person {
    var pet: Pet?
}

class Pet {
    var name: String
    
    var favoriteToy: Toy?
    
    init(name: String) {
        self.name = name
    }
}

class Toy {
    var name: String
    
    init(name: String) {
        self.name = name
    }
}</pre>
<p>So here we have a person that may or may not have a pet.  Then we have a pet that has a name, but may not have a favorite toy.  Then we have a toy that has a name.  Let&#8217;s say we wanted to say something about that favorite toy:</p>
<pre class="lang:swift decode:true">if let someToy = jim.pet?.favoriteToy?.name {
    print("This person's pet likes the \(someToy).")
} else {
    print("This person's pet does not have a favorite toy")
}</pre>
<p>By adding those question marks, we basically ask it whether there is a valid value or not.  If pet was nil, or favoriteToy was nil, the optional binding would fail, and we would drop to the else clause.</p>
<p>Basically, optional chaining just returns an optional of whatever you query for at the end.  Even though &#8220;name&#8221; in favoriteToy is not optional in the &#8220;Toy&#8221; class, as a result of it being called from optional chaining, you either get a nil if there is no name since it cannot be reached (either from pet or favoriteToy being nil), or you the value.  But since it has to be able to return nil if it cannot reach the value, the response must be an optional.</p>
<h2>Implicitly Unwrapped Optionals</h2>
<p>I personally feel a bit uneasy about these.  Implicitly unwrapped optionals are pretty much what they sound like.  They are an optional variable that is automatically unwrapped.  This is another way that you don&#8217;t have to have exclamation marks everywhere, because the forced unwrapping is built in.  It is so similar to forced unwrapping, its notation is identical, just used at the variable&#8217;s declaration time:</p>
<pre class="lang:swift decode:true">var shouldBeASensorReadingHere: Int! = 42
var testAnswer = 30 + shouldBeASensorReadingHere</pre>
<p>This is as opposed to a normal optional:</p>
<pre class="lang:swift decode:true">var unsureSensorReading: Int? = 42
var testAnswerTwo = 30 + unsureSensorReading!</pre>
<p>Again, it is a simple example, and either one is about the same amount of code, all that is changed is where you put the exclamation mark.  In a more complex algorithm though, there could be many places to unwrap it and if you, for some reason, don&#8217;t want to use optional binding, this could save a lot of exclamation marks.</p>
<h3>Why use implicitly unwrapped Swift Optionals</h3>
<p>There aren&#8217;t too many reasons nowadays outside of places Xcode sets for you, like for IBOutlets.  The main places they would be used are for places that need to be optional because it can&#8217;t be known at initialization time, but will be a valid variable by the time it is used.  IBOutlets are a great example of this.  They aren&#8217;t connected to anything when a ViewController is initialized, if you call RIGHT after initialization, they will be nil, and probably crash your program.  However, people don&#8217;t usually USE them at that point.  The outlets are used after the ViewController is loaded and connected to its view, so by the time ViewDidLoad is called, the IBOutlets have been connected and are no longer nil, so it would be unnecessarily onerous to need them to use Optional syntax for something that is effectively never nil in normal operation.</p>
<p>The other place is when using Objective-C APIs that have not been updated to the Swifter way to handle variables.  With Apple having updated their APIs a while back, and Objective-C nullability annotations able to be used, this should hopefully be a thing of the past, but if you use some legacy code or an Objective-C third party library, stuff might still bridge over as implicitly unwrapped optionals.  Using it elsewhere, I say is at your own risk.</p>
<p>One other thing to note, an implicitly unwrapped optional is still a normal Swift optional, so you can still use optional binding, testing against nil, or optional chaining if you want to be safe anyway, it just is not enforced like it is with normal optionals.</p>
<h2>Conclusion</h2>
<p>I know this post was a bit of a long one, but I think those two aspects of Swift optionals deserve a little extra time to talk about.  I in particular was confused about the use of implicitly unwrapped optionals for Objective-C classes earlier in Swift&#8217;s development, and while I&#8217;m still not the biggest fan, I see better why they are used.  Any NSObject COULD be nil, and thus must be an optional, but in much of Apple&#8217;s APIs, they are used as if they are not (like the UITableView and NSIndexPath parameters), since that would make little sense in a call to cellForRowAtIndexPath.</p>
<p>I knew that if it was confusing me, that I had to share it here, since there is probably somebody out there that felt similar to me on that subject.  Though this is changing as Apple goes through and updates the APIs to use non-Optional variables instead of implicitly unwrapped optionals, it is good to know for the times when they still choose to do so.</p>
<p>With the addition of nullability annotations in Objective-C, I have seen implicitly unwrapped optionals used less and less, which is a great benefit for Swift code safety.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-OptionalsCHImplicitlyUnwrapped" target="itunes_store" rel="noopener noreferrer">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/optional-chaining-implicitly-unwrapped-optionals-swift/">Optional Chaining and Implicitly Unwrapped Optionals in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swift Optionals &#8211; Declaration, Unwrapping, and Binding</title>
		<link>https://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 17 Jul 2014 22:38:16 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[optionals]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=260</guid>

					<description><![CDATA[<p>Continuing our conversations about variables in Swift, lets move on to one of the more important additions in this realm to Swift, Optionals.  In Swift, all normal variables must have a value.  In Objective-C, C-based variables (primitives) always had to have a value, but object types could either be a valid object, or a pointer [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals &#8211; Declaration, Unwrapping, and Binding</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Continuing our conversations about variables in Swift, lets move on to one of the more important additions in this realm to Swift, Optionals.  In Swift, all normal variables must have a value.  In Objective-C, C-based variables (primitives) always had to have a value, but object types could either be a valid object, or a pointer to nil.  Swift optionals allow you to make any type in Swift into a nil-able type (though this nil is not exactly the same as an Objective-C nil).<br />
<span id="more-260"></span></p>
<h2>The Reason for Swift Optionals</h2>
<p>While Swift optionals are new, they have their roots in Objective-C.  You could set any pointer based variable to nil like NSString, NSDate, etc.  However, you could not do the same with primitive C types like ints, doubles, etc.  You would have specific sentinel values to deal with them, which were valid numbers, just not often used.  In the case of ints, it was NSNotFound, which was mapped to NSIntegerMax.  What if you happened to have a valid value of 2,147,483,647 on a 32-bit system, or 9,223,372,036,854,775,807 on a 64-bit system.</p>
<p>It&#8217;s unlikely, but it could be some big-data program, or maybe something displaying the number of neutrinos going through Cupertino during a certain time period, who knows?  If you are curious, apparently 65 billion neutrinos pass through one square centimeter of Earth every second (according to <a title="Neutrino - Wikipedia, the free encyclopedia" href="http://en.wikipedia.org/wiki/Neutrino">Wikipedia</a>), and with Cupertino being 29.16 km², if my math is correct, that comes out to about 487 µsec.</p>
<p>Anyway, that tangent aside, Apple decided to have a single sentinel value to refer to an invalid state, instead if NSNotFound, NSNULL, and many others, they just boiled down to nil, via Swift optionals.  So now, you can make any variable, be it an Integer, String, custom class, or even a structure, into a nil-able type.  It is actually rather interesting, and surprisingly simple how it is implemented under the hood.  To Swift, an optional is just this:</p>
<pre class="lang:swift decode:true">enum myOptional&lt;T&gt; {
    case None
    case Some(T)
}</pre>
<p>It is an enumeration with 2 possible states, None or Some.  None handles returning nil for a value, while some actually holds the value.  This is a generic enumeration, and if you&#8217;re curious how both of those work, check out my future posts <a title="Enumerations in Swift" href="http://www.codingexplorer.com/enumerations-swift/">Enumerations in Swift</a> and <a title="Generic Types in Swift" href="http://www.codingexplorer.com/generic-types-swift/">Generic Types in Swift</a>.  The &#8220;Some&#8221; case is using the ability for enums to have values associated with their states, so in the parenthesis you would enter the type of value you would want to associate with that case.  So if it would return a String, you would put String in the parenthesis.  In this case, it is a generic, so the Optional enum is made of type &#8220;T&#8221;, which is a placeholder for whatever type is actually specified, and so we put T in as the type for the &#8220;Some&#8221; case value.</p>
<h2>Using Swift Optionals</h2>
<p>If you are not sure about something, wouldn&#8217;t you ask a question about it?  Apparently, Apple thought something similar because that is basically how you declare an optional.  Behold:</p>
<pre class="lang:swift decode:true">var optionalInteger: Int?

var   normalInteger: Int          //For Comparison</pre>
<p>Seems simple enough.  You can then write to it like any other Integer, no special boxing required to <span style="text-decoration: underline;"><strong>set</strong></span> it.  As we have already discussed, since it is a Swift optional, you can set it to nil, also with no special boxing.</p>
<pre class="lang:swift decode:true">var optionalInteger: Int?
optionalInteger = 42
optionalInteger = nil
</pre>
<p>The same is not true for reading it though.  Swift expects values to be standard, non-optional types, so to actually used them you have to change them back from Swift optionals to standard Swift types.  There are a few ways to do so:</p>
<h3>Forced unwrapping</h3>
<p>One way to use Swift Optionals in places that don&#8217;t take them, is to forcefully change them back into normal variables.  Apparently you question a variable to make it into an optional, and you yell at at it to forcefully unwrap it:</p>
<pre class="lang:swift decode:true">normalInteger = optionalInteger! + 5</pre>
<p>Yep, that exclamation point forcefully unwraps it.  There is a problem though.  You have to check it for nil before you do this to be safe.  If you try this with the optional containing a nil, a runtime error will occur.  One way to deal with this, is to check for it in an if statement:</p>
<pre class="lang:swift decode:true">if optionalInteger != nil {
    normalInteger = optionalInteger! + 5
} else {
    print("Nothing here")
}</pre>
<p>Now it will only do the unsafe unwrapping if there is a non-nil value in the Swift optional.</p>
<h3>Optional Binding</h3>
<p>For this bit of code, that is fine, but what if we had to use optionalInteger more times in that if statement.  Would you want to remember to type that exclamation point everywhere?  You might forcefully unwrap it and assign it to a temporary normal variable, and that would be much better.  What if you could simply do that at the same time you check whether it is a valid Integer?</p>
<pre class="lang:swift decode:true">if let tempInteger = optionalInteger {
    normalInteger = tempInteger + 12
} else {
    print("Still nothing here")
}</pre>
<p>With that &#8220;<span style="color: #bb2ca2;">if let</span>&#8221; syntax, you do just that, and store an unwrapped version of &#8220;optionalInteger&#8221; in &#8220;tempInteger&#8221;, or you skip that condition and go to the else.  This is called &#8220;Optional Binding.&#8221;</p>
<h2>Conclusion</h2>
<p>There are a few more things to talk about with Swift optionals, but I think this is a good place to start.  Check out my next post about <a title="Optional Chaining and Implicitly Unwrapped Optionals in Swift" href="http://www.codingexplorer.com/optional-chaining-implicitly-unwrapped-optionals-swift/">Optional Chaining and Implicitly Unwrapped Optionals in Swift</a>, as well as about another way to either unwrap an Optional, or return a default value with the <a title="Nil Coalescing in Swift" href="http://www.codingexplorer.com/nil-coalescing-swift/">Nil Coalescing Operator in Swift</a>.  Optionals are a very powerful tool in Swift, and as such we must be careful, that is, unless we <em>want</em> to cause a runtime error.</p>
<p>Also, released in Swift 2, there is another way to unwrap Optionals, particularly helpful to get return from a method early if a Swift Optional is nil, or an invalid value, the Guard statement.  You can read more about it in the post <a href="http://www.codingexplorer.com/the-guard-statement-in-swift-2/">The Guard Statement in Swift 2</a>.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftOptionalsDeclareUnwrap" target="itunes_store" rel="noopener noreferrer">The Swift Programming Language &#8211; Apple Inc.</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals &#8211; Declaration, Unwrapping, and Binding</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Computed Properties in Swift</title>
		<link>https://www.codingexplorer.com/computed-properties-in-swift/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 15 Jul 2014 03:20:53 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[properties]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=247</guid>

					<description><![CDATA[<p>Continuing the discussion about variables in Swift, let us move on to properties, which are basically Swift constants or variables used in a class, structure, or enumeration.  More specifically, they are stored values for a class, structure, or enumeration, that have getter and setter methods that can be modified.  You can leave them alone, and [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/computed-properties-in-swift/">Computed Properties in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Continuing the discussion about variables in Swift, let us move on to properties, which are basically Swift constants or variables used in a class, structure, or enumeration.  More specifically, they are stored values for a class, structure, or enumeration, that have getter and setter methods that can be modified.  You can leave them alone, and they will do what they should (return the value or set a new one).  The getters and setters can be overridden, like to override the setter to allow you to check if the input value is valid before storing it.  Getters and setters are also called &#8220;accessors&#8221; and &#8220;mutators&#8221; respectively.  Take your pick, but for me, I&#8217;m going to just call them getters and setters.</p>
<p>There are a few more aspects to properties, but today, we will be talking about a specific type of property.<span id="more-247"></span></p>
<h2>Swift Computed Properties</h2>
<p>Swift computed properties are properties that do not have their own backing store and are particularly useful for conversions.  Here&#8217;s an example of a computed property.  Lets say our program has a custom class that stores time.  Yes, we could use <a title="Displaying a human readable NSDate" href="http://www.codingexplorer.com/displaying-a-human-readable-nsdate/">DateComponents</a>, but bear with me here to show a possible use for Swift computed properties.  When we use this class, we may want to use it in seconds, minutes, hours, days, etc.  We could set up methods to calculate that for us, and we would in other languages, but in Swift, we could write a class like so:</p>
<pre class="lang:swift decode:true">class Time {
    var seconds:Double = 0
    
    init(seconds: Double) {
        self.seconds = seconds
    }
    
    var minutes: Double {
        get {
            return (seconds / 60)
        }
        set {
            self.seconds = (newValue * 60)
        }
    }
    
    var hours: Double {
        get {
            return (seconds / (60 * 60))
        }
        set {
            self.seconds = (newValue * (60 * 60))
        }
    }
    
    var days:  Double {
        get {
            return (seconds / (60 * 60 * 24))
        }
        set {
            self.seconds = (newValue * (60 * 60 * 24))
        }
    }
}</pre>
<p>In this class, we first created a Double variable that stores &#8220;seconds.&#8221;  We then created 3 computed properties for minutes, hours, and days.  The getters divide the seconds by the appropriate scaling factor, and return that.  The setters multiply by the appropriate scaling factor and save that in the instance variable.</p>
<p>One important thing to note is that computed properties must be created as variables with the <span style="color: #bb2ca2;">var</span> keyword.  They cannot be written as constants, even if it is a read-only computed property.</p>
<p>For the setters in these computed properties, you probably noticed the &#8220;newValue&#8221; variable.  That is the default name for whatever new value is sent to the setter.  The setter for this property is actually:</p>
<pre class="lang:swift decode:true">set(newValue) {
    self.seconds = (newValue * 60)
}</pre>
<p>You can change that to whatever you want, if you want it really obvious, since this one is the one for minutes, you could do something like this:</p>
<pre class="lang:swift decode:true">set(newMinutes) {
    self.seconds = (newMinutes * 60)
}</pre>
<p>When you do not specify that input parameter to the setter, &#8220;newValue&#8221; is the one automatically generated for you.  If you change it to &#8220;newMinutes&#8221; like this, &#8220;newValue&#8221; no longer is generated, and starts showing an error if you changed the input parameter name, but not the one used inside (change the &#8220;set&#8221; one, but not the &#8220;newValue * 60&#8221; one).</p>
<p>One thing to note, the &#8220;newValue&#8221; part is not specific to computed properties.  It is also used in property observers, as well as subscripts.  I&#8217;ll probably cover those in a future post.  Check out my post on <a title="Swift Property Observers" href="http://www.codingexplorer.com/swift-property-observers/">Swift Property Observers</a> and <a title="Custom Subscripts in Swift" href="http://www.codingexplorer.com/custom-subscripts-swift/">Custom Subscripts in Swift</a> for more details on those uses of newValue.</p>
<p>You would use this class as such:</p>
<pre class="lang:swift decode:true">let countdown = Time(seconds: 42.0)

countdown.minutes              //Reading value (Results in 0.7 minutes)

countdown.hours = 1            //Setting value (Internally stored as 3,600 seconds)

countdown.minutes              //Reading value (Results in 60.0 minutes)

countdown.seconds              //Reading value (Results in 3,600 seconds)
</pre>
<p>As you can see, you just access Swift computed properties like they were a normal property via dot syntax.  They just happen to not have their own storage, and in this case, all rely on the storage for the seconds property.</p>
<h2>Conclusion</h2>
<p>I am definitely a fan of computed properties in Swift.  Could we just use a method instead?  Sure, but this just seems cleaner to treat them like they were member variables when you are calling the class that holds them.  While I am using them for unit conversions, there are plenty of other uses for computed properties.  The example in Apple&#8217;s iBook for instance, shows it being used in a struct that defines a rectangle.  In that case, it stores the origin as a point (which is another struct they make in the example), and lets you modify the &#8220;center&#8221; of the rectangle via computed properties.  In that case, they just add half of the appropriate dimension to the origin (origin.y + (size.height/2), for example).  Nonetheless, they have many uses, unit conversions are just an easy example.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftComputedProperties" target="itunes_store" rel="noopener noreferrer">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Swift 101 - Classes, Variables, Properties &amp; Methods | Kevin McNeish | iPhone Life" href="http://www.iphonelife.com/blog/31369/swift-101-classes-variables-properties-methods">Swift 101 &#8211; Classes, Variables, Properties &amp; Methods | Kevin McNeish | iPhone Life</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/computed-properties-in-swift/">Computed Properties in Swift</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Swift Variables and Constants</title>
		<link>https://www.codingexplorer.com/swift-variables/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 08 Jul 2014 00:13:13 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=194</guid>

					<description><![CDATA[<p>How do you store data in a program?  Well, you store it in variables, but you already knew that didn&#8217;t you?  Here is my first post about Swift variables, where we discuss their declaration and definition.  In particular, we will mostly be discussing the concept of Swift variables and constants. Swift Variables and Constants There are [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/swift-variables/">Swift Variables and Constants</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>How do you store data in a program?  Well, you store it in variables, but you already knew that didn&#8217;t you?  Here is my first post about Swift variables, where we discuss their declaration and definition.  In particular, we will mostly be discussing the concept of Swift variables and constants.</p>
<p><span id="more-194"></span></p>
<h2>Swift Variables and Constants</h2>
<p>There are 2 ways to store a value in Swift, as a variable, or a constant.  Here is how to create each:</p>
<pre class="lang:swift decode:true">var myNumber  = 45     //Variable
let theAnswer = 42     //Constant
</pre>
<p>That seems simple enough.  From other programming languages, one might think, <span style="color: #bb2ca2;">var</span> is a type for a variable and <span style="color: #bb2ca2;">let</span> is the type for a constant, right?  Well, while the first may be true in C#, it is not in Swift.  In Swift, these are just keywords defining whether the stored value (irrelevant of its specific type) is stored as a variable or a constant.</p>
<p>That leads us to the next point, notice the lack of an explicit type there?  Swift has implicitly typed these stored values.  You CAN set the type if you want, particularly if you do not initialize them, but that is not the case here.  Here, the compiler saw that I wanted to store 45 or 42, and realized, &#8220;Well, 42 is an Int, so &#8216;theAnswer&#8217; must be storing an Int!&#8221;</p>
<p>If you really want to type your variables, you would do so this way:</p>
<pre class="lang:swift decode:true">var theNumber: Double</pre>
<p>You must always initialize your <span style="color: #bb2ca2;">let</span> constants, even if you explicitly type them.  One reason to explicitly type a constant, as suggested in Apple&#8217;s Swift Language Reference, is if you wanted a double, but only wanted to type an Int literal, i.e.:</p>
<pre class="lang:swift decode:true">let myExpValue: Double = 29</pre>
<p>So it would actually store 29.0 as the value for myExpValue, even though you only typed 29.  Just for fun, I tried the opposite, doesn&#8217;t work so well.  It gives the error, &#8220;Cannot convert value of type &#8216;Double to specified type &#8216;Int&#8217;.&#8221;  The error does make sense though.  You have to explicitly convert it to work.</p>
<h2>Use of Swift Constants</h2>
<p>As one would expect, a numeric constant is a constant, so when you try to edit it, a compiler error is shown:</p>
<pre class="lang:swift decode:true">let theAnswer = 42
theAnswer = 21
//error: cannot assign to value: 'theAnswer' is a 'let' constant</pre>
<p>That makes sense, but really seems to limit the use for <span style="color: #bb2ca2;">let</span> stored values?  I mean, constants are great and all, but I don&#8217;t tend to have them all over my code, usually just a few per class, usually for <a title="Eliminating stringly-typed code in Objective-C" href="http://corner.squareup.com/2014/02/objc-codegenutils.html">stringly typed</a> (not a typo, but a nickname) things like Notifications.</p>
<p>Apple seems to use <span style="color: #bb2ca2;">let</span> all over the place, so why would you want to use constants everywhere?</p>
<h3>Convenience Variables</h3>
<p>Well, for one, I&#8217;m sure most of us have made temporary variables that do not change after their initialization.  Something like this example:</p>
<pre class="lang:objc decode:true">CGFloat PADDING_OUTER = 5;
CGFloat textLabelHeight = [@"0" sizeWithAttributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]}].height;
CGFloat detailLabelHeight = [@"0" sizeWithAttributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1]}].height;
    
CGFloat totalHeight = PADDING_OUTER + textLabelHeight + detailLabelHeight + PADDING_OUTER;
    
self.tableView.rowHeight = totalHeight;</pre>
<p>Sure, we could have done:</p>
<pre class="lang:objc decode:true ">self.tableView.rowHeight = 5 + [@"0" sizeWithAttributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]}].height + [@"0" sizeWithAttributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1]}].height + 5;</pre>
<p>But which is more readable?  PADDING_OUTER, textLabelHeight, detailLabelHeight, and totalHeight are all PERFECT places to use <span style="color: #bb2ca2;">let</span>.</p>
<h3>Class References</h3>
<p>Secondly, the assignment is constant, but are its contents?  For reference types (and Classes are reference types), the contents usually aren&#8217;t.  As such, you could do something like this:</p>
<pre class="lang:swift decode:true">let nf = NumberFormatter()
nf.numberStyle = .currency

if let formattedNumber = nf.string(from: 7.145) {
    print(formattedNumber)
    //Output:  $7.14
}</pre>
<p>We never reassign &#8220;nf&#8221; to another NSNumberFormatter, but we do change some of its properties, in this case the numberStyle.  This another great use of <span style="color: #bb2ca2;">let</span> in Swift.  If you are curious about that &#8220;if let&#8221; statement, that is something called Optional Binding, which you can read about in the post <a href="http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/">Swift Optionals – Declaration, Unwrapping, and Binding</a>.  It&#8217;s basically a fancy way to check if an optional is equal to nil, and if it is not, to store it to a constant for later use.  The stringFromNumber method returns an optional string, so if it can make a valid string, the optional contains that String, if it cannot, it returns nil.  This is why we needed this optional binding, to get the real Swift String out of that Optional.</p>
<h2>Conclusion</h2>
<p>In this post, I have often used the term &#8220;stored value&#8221; to refer to variables and constants, as opposed to saying variable variables and variable constants, (suddenly I am reminded of &#8220;Mario Mario&#8221; and &#8220;Luigi Mario&#8221; from the Mario Bros. Movie).  For future posts though, unless I am talking about the differences again, I will probably just refer to them both as variables for the sake of simplicity.  I will refer to constants as such when I need to specify the difference, but more often than not, I will probably refer to our NSNumberFormatter &#8220;nf&#8221; from above as variable, even if I do make it a constant <span style="color: #bb2ca2;">let,</span> in the code.</p>
<p>I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on the <a href="http://www.codingexplorer.com/contact/">Contact Page</a>, or on Twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11&amp;uo=4&amp;at=10lJ3x&amp;ct=blog-SwiftVariables" target="itunes_store" rel="noopener noreferrer">The Swift Programming Language &#8211; Apple Inc.</a></li>
<li><a title="Learn Swift From Objective-C : Variables, Classes, Methods and Properties" href="http://codewithchris.com/learn-swift-from-objective-c/">Learn Swift From Objective-C : Variables, Classes, Methods and Properties &#8211; Code With Chris</a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/swift-variables/">Swift Variables and Constants</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>MFMailComposeViewController &#8211; Send email in your apps</title>
		<link>https://www.codingexplorer.com/mfmailcomposeviewcontroller-send-email-in-your-apps/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 28 Jun 2014 06:15:05 +0000</pubDate>
				<category><![CDATA[Objective-C]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=207</guid>

					<description><![CDATA[<p>Have you wanted to send an e-mail from your app and pre-populate the fields like the recipient, subject, or body text?  Apple made it pretty easy with MFMailComposeViewController.  There is a bit of setup, but most of its actual implementation is pretty easy. Loading MessageUI, MFMailComposeViewController&#8217;s framework So, firstly, we have to load a framework.  This functionality [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/mfmailcomposeviewcontroller-send-email-in-your-apps/">MFMailComposeViewController &#8211; Send email in your apps</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Have you wanted to send an e-mail from your app and pre-populate the fields like the recipient, subject, or body text?  Apple made it pretty easy with MFMailComposeViewController.  There is a bit of setup, but most of its actual implementation is pretty easy.</p>
<p><span id="more-207"></span></p>
<h2>Loading MessageUI, MFMailComposeViewController&#8217;s framework</h2>
<p>So, firstly, we have to load a framework.  This functionality isn&#8217;t built in, so we have to get it from somewhere.</p>
<p>Click on your project in the Project Navigator.  In there, click on your Target application.  Then go to the &#8220;Build Phases&#8221; tab, and then open the &#8220;Link Binary With Libraries&#8221; section.  There are probably a few things here already like UIKit.  You will then click on the + button in the lower left corner (in Xcode 5).  In there, you can either scroll down and look, or just search for message, and then highlight the MessageUI.framework option, and click Add.  This will add the framework to your project.</p>
<p>Next, we need to add a couple things to the top of your class, the import for this, and a protocol we&#8217;ll need for later:</p>
<pre class="lang:objc decode:true ">#import &lt;MessageUI/MessageUI.h&gt;
@interface yourViewController ()</pre>
<p>Where I am saying that you add the &lt;MFMailComposeViewControllerDelegate&gt; to your classes beginning interface area.</p>
<h2>MFMailComposeViewController&#8217;s Mail Field Settings</h2>
<p>Here you set the default settings for the various fields in your email.</p>
<p>The available settings are:</p>
<ul>
<li>setSubject:</li>
<li>setToRecipients:</li>
<li>setCcRecipients:</li>
<li>setBccRecipients:</li>
<li>setMessageBody:isHTML:</li>
<li>addAttachmentData:mimeType:fileName:</li>
</ul>
<p>For my app, I just needed the subject, toRecipients, so that is what I&#8217;ll show here.  You also need to determine if the user is even capable of sending email, like if they have an email account set up in the mail app.  Luckily for us, there is a class method that shows us just that.</p>
<h2>Finally presenting the MFMailComposeViewController</h2>
<p>Here is the actual code to show the email composer:</p>
<pre lang="objc">if ([MFMailComposeViewController canSendMail])
{
    MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
    mail.mailComposeDelegate = self;
    [mail setSubject:@"Sample Subject"];
    [mail setMessageBody:@"Here is some main text in the email!" isHTML:NO];
    [mail setToRecipients:@[@"testingEmail@example.com"]];

    [self presentViewController:mail animated:YES completion:NULL];
}
else
{
    NSLog(@"This device cannot send email");
}</pre>
<p>So first, we check that class method to see if the user can even send email.  This will return a BOOL, and if not, we log something to the console for debugging.</p>
<p>If the user can, we create an instance of MFMailComposeViewController, and set its delegate to self.  I will show you momentarily how to properly respond to this delegate call.</p>
<p>Then, we set the subject to some string, set the message body to some string (and say whether it is HTML or not, in my case it is not), and the recipients.</p>
<p>Now, notice that I said recipients plural.  It actually takes an NSArray of NSStrings for that method.  In this case I am just using the Objective-C Literal syntax (see <a title="Objective-C Literals — Clang 3.5 documentation" href="http://clang.llvm.org/docs/ObjectiveCLiterals.html">Clang Documentation</a> for more information) to create an NSArray of objects separated by commas (but since I only have one, that is unnecessary).</p>
<p>After that, just tell self to present the view controller we just added all of these settings to and voilà!</p>
<h2>MFMailComposeViewControllerDelegate</h2>
<p>Now we have to set up what to do when the delegate is called.  This delegate has only one instance method, and it is called when the user is ready (one way or another) to dismiss the mail composer.</p>
<p>Here is a sample of how to respond to the delegate:</p>
<pre lang="objc">- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result) {
        case MFMailComposeResultSent:
            NSLog(@"You sent the email.");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"You saved a draft of this email");
            break;
        case MFMailComposeResultCancelled:
            NSLog(@"You cancelled sending this email.");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed:  An error occurred when trying to compose this email");
            break;
        default:
            NSLog(@"An error occurred when trying to compose this email");
            break;
    }

    [self dismissViewControllerAnimated:YES completion:NULL];
}</pre>
<p>So the result contains some MFMailComposeResult, and it allows you to handle it however you see fit, such as if they save it, maybe you could increment a count of emails saved by your app, I guess.  Just for demonstration, I am just logging them out to the console for now.</p>
<h2>Conclusion</h2>
<p>There you have MFMailComposeViewController in all its glory.  It is a very simple view controller, but it lets you get the job done efficiently, and in a very easy to read manner.  To make this a bit easier, I have created a <a title="CodingExplorer/CEBEmailTutorial · GitHub" href="https://github.com/CodingExplorer/CEBEmailTutorial">sample project on GitHub</a> that shows how this works in context.  To test this fully though, you do need to run it on a device.</p>
<p>I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources</h2>
<ul>
<li><a title="iOS Programming 101: How To Send Email in iPhone App with MessageUI" href="http://www.appcoda.com/ios-programming-101-send-email-iphone-app/"><span style="color: #000000;">iOS Programming 101: How To Send Email in iPhone App with MessageUI &#8211; AppCoda</span></a></li>
<li><a title="iOS SDK: Send E-mail In-App - Tuts+ Code Tutorial" href="http://code.tutsplus.com/tutorials/ios-sdk-send-e-mail-in-app--mobile-7982"><span style="color: #000000;">iOS SDK: Send E-mail In-App &#8211; Tuts+ Code Tutorial</span></a></li>
<li><a title="MFMailComposeViewController Class Reference" href="https://developer.apple.com/library/ios/documentation/MessageUI/Reference/MFMailComposeViewController_class/Reference/Reference.html"><span style="color: #000000;">MFMailComposeViewController Class Reference &#8211; Apple</span></a></li>
<li><a title="MFMailComposeViewControllerDelegate Protocol Reference" href="https://developer.apple.com/library/ios/documentation/MessageUI/Reference/MFMailComposeViewControllerDelegate_protocol/Reference/Reference.html"><span style="color: #000000;">MFMailComposeViewControllerDelegate Protocol Reference &#8211; Apple</span></a></li>
</ul>
<p>The post <a href="https://www.codingexplorer.com/mfmailcomposeviewcontroller-send-email-in-your-apps/">MFMailComposeViewController &#8211; Send email in your apps</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Replace Keyboard with UIDatePicker</title>
		<link>https://www.codingexplorer.com/replace-keyboard-with-uidatepicker/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 12 Jun 2014 06:52:17 +0000</pubDate>
				<category><![CDATA[Objective-C]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=198</guid>

					<description><![CDATA[<p>I thought I might write a smaller post today.  This is something I needed to do in one of my apps, and thought I would share a bit of how it is done.  The actual action to take here is pretty easy and short, but I will discuss a few other things I learned while [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/replace-keyboard-with-uidatepicker/">Replace Keyboard with UIDatePicker</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I thought I might write a smaller post today.  This is something I needed to do in one of my apps, and thought I would share a bit of how it is done.  The actual action to take here is pretty easy and short, but I will discuss a few other things I learned while doing it.<span id="more-198"></span></p>
<p>In this app, one thing the user has to do is enter a date.  I figured the best way was to have a user tap on a UITextField and instead of the keyboard, have it show a UIDatePicker.  The textfield would later be used for just displaying the information selected in that UIDatePicker.</p>
<h2>Actually replacing the Keyboard with UIDatePicker</h2>
<p>Since I said the main thing to do was easy, lets get right into it.  Here is the code to replace the keyboard with a UIDatePicker:</p>
<pre lang="objc">UIDatePicker *datePicker = [[UIDatePicker alloc] init];
[self.someTextField setInputView:datePicker];</pre>
<p>And we&#8217;re done.  Like I said, it was really easy.</p>
<h2>Setting UIDatePicker Options</h2>
<p>So what else is there to this?  Well, in the case of my app, this default date picker shows time of day, which is meaningless in my app, and doesn&#8217;t show the year, which I should have.  By default, this will generate a UIDatePicker that allows you to set the date by day and time (as in one tumbler is &#8220;Sun Jun 15&#8221;, next is hour, next is minutes, and finally AM/PM).  I just need dates, so then we need to set up the datePicker to do that:</p>
<pre lang="objc">UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[self.someTextField setInputView:datePicker];</pre>
<p>For reference, here are all of the options for the UIDatePickerMode enum:</p>
<ul>
<li>UIDatePickerModeTime &#8211; (Hour, minute, AM/PM)</li>
<li>UIDatePickerModeDate &#8211; (Month, Day, Year)</li>
<li>UIDatePickerModeDateAndTime &#8211; (Default, (Weekday Month Day), HH, MM, AM/PM)</li>
<li>UIDatePickerModeCountDownTimer &#8211; (Hours (up to 24) and minutes)</li>
</ul>
<p>The default date that it starts scrolling from is the the date the UIDatePicker was created.  If you want to set it to a different date, you can just set the UIDatePicker&#8217;s date property (or send a message to setDate).</p>
<h2>Updating the UITextField when the UIDatePicker value changes</h2>
<p>In the case of my app, I also wanted it to update what is shown in that text box as we scroll around.  To do that, I have to trigger a method somewhere to handle doing that.  In Interface Builder, you can do that via Control dragging from a control to the assistant editor window.  Here you have to set it via code, but it&#8217;s pretty easy, here is the creation of our UIDatePicker with that added:</p>
<pre lang="objc">UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(updateTextField:)
     forControlEvents:UIControlEventValueChanged];
[self.someTextField setInputView:datePicker];</pre>
<p>Then elsewhere you have to create the updateTextField method:</p>
<pre lang="objc">-(void)updateTextField:(UIDatePicker *)sender
{
    self.someTextField.text = [self.dateFormat stringFromDate:sender.date];
}</pre>
<h2>Hiding the Keyboard afterward</h2>
<p>Finally, like any keyboard on your screen, you must have a way to dismiss it.  I want it to hide if somebody clicks outside of the keyboard area, so I use this:</p>
<pre lang="objc">- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}</pre>
<p>This overrides the main touchesBegan on the view controller.  When it is run, it first sends the same command to its superclass, so that if there is anything the view itself would do otherwise with these touches, it does.  I do not know if this is necessary in this case, but I think it is probably for the best.  Anyway, the main part is sending the message to the view, saying to end the editing, and as such hide the keyboard.</p>
<h2>A note on performance</h2>
<p>You may notice that I did not say WHERE to put the commands above to create your UIDatePicker.  Here is the reason why.  I first wrote the program, loading that in viewDidLoad.  I was testing on an iPhone 4, and found that setting the mode (assigning to datePicker.datePickerMode), took about 150ms.  Considering the rest of my startup of loading system resources was about 600 ms, and every other command was in the 10s of milliseconds, I felt I had to do something about it.</p>
<p>I had two options:  Put it on a background queue in viewDidLoad, or just generate it when I need it.  Since the iPhone 4 has only 1 core, the first may not help as much (I THINK it should help somewhat, but I have not done a LOT of work in multithreading yet), but even if it did, it would have that UIDatePicker just waiting in memory, when it might not even be needed.</p>
<p>For my app, you should set this part when you first get the app, but probably won&#8217;t need to set it again for quite some time.  If somebody opens my app to check something and doesn&#8217;t need to set this date, lets say twice a day for 9 months, that&#8217;s about 548 loads, and at 150 ms each, that&#8217;s 82.2 seconds.  Yes, that is about a minute and a half spread over 9 months, but it still doesn&#8217;t need to be there if they don&#8217;t change the date often.  Premature optimization?  Perhaps, but it was so little to fix, I thought I might as well, especially since it increases startup time by 25% or so unnecessarily.</p>
<p>So for me, I decided to run this when somebody taps down on the text box.  If they drag their finger off, it did load this unnecessarily, but I would rather load it when the user looks like they might need it, as opposed to just when the app is opened and may not need it.  So I attached an action in interface builder to the text box touch down event, and added this:</p>
<pre lang="objc">- (IBAction)someTextFieldTouchDown:(UITextField *)sender
{
    if (self.someTextField.inputView == nil)
    {
        UIDatePicker *datePicker = [[UIDatePicker alloc] init];
        datePicker.datePickerMode = UIDatePickerModeDate;
        [datePicker addTarget:self action:@selector(updateTextField:)
             forControlEvents:UIControlEventValueChanged];
        [self.someTextField setInputView:datePicker];
    }
}</pre>
<p>So that if there is no inputView set (the default is nil, which means to show the normal keyboard), then create this and add it.  If not, don&#8217;t bother and do nothing.  This way, if they tap down, it starts loading it, so by the time they lift their finger it is done, and they see the UIDatePicker.  There might be a small delay, but it is not very noticeable, and it is not at startup.</p>
<h2>Conclusion</h2>
<p>I should really learn from podcasts and not say &#8220;this will be a short one&#8221;, oh well, at least it was informative, right?  I did say that I &#8220;might&#8221; write a smaller post, not that I necessarily &#8220;would&#8221;.  Anyway, that is how I replaced the keyboard with a UIDatePicker, and some of the things I learned along the way.  Also, if you want to change how the date is written in the text box (instead of the default), you might want to read my post <a title="Displaying a human readable NSDate" href="http://www.codingexplorer.com/displaying-a-human-readable-nsdate/">Displaying a human readable NSDate</a>.</p>
<p>I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/replace-keyboard-with-uidatepicker/">Replace Keyboard with UIDatePicker</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Getting started with NSNotificationCenter</title>
		<link>https://www.codingexplorer.com/getting-started-with-nsnotificationcenter/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 10 Jun 2014 00:43:11 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<category><![CDATA[Objective-C]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=195</guid>

					<description><![CDATA[<p>Have you ever wanted to alert other classes of your app of some event from another one? Sure, you could have your class poll the other one and keep asking if something has changed, but that seems to be wasteful, since in many cases, there usually won&#8217;t be.  You could even not bother with polling, and just read [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/getting-started-with-nsnotificationcenter/">Getting started with NSNotificationCenter</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Have you ever wanted to alert other classes of your app of some event from another one?</p>
<p>Sure, you could have your class poll the other one and keep asking if something has changed, but that seems to be wasteful, since in many cases, there usually won&#8217;t be.  You could even not bother with polling, and just read it back in all the time, but if there has been no change, that again is wasteful of processing time, power, etc.  To avoid these issues, I have found that  NSNotification Center is a great answer to this problem.  You can just have your class subscribe to the Notification, and then when it alerts your class that there has actually been an event you&#8217;ve been waiting for, you THEN can call that class and read in what is necessary, or react appropriately.</p>
<p><span id="more-195"></span></p>
<p>Now if you have been reading this blog for a bit, you might think, &#8220;Yeah yeah, we know about NSNotification center, you wrote about it in a couple of your earlier posts:  <a title="Supporting Dynamic Type for iOS7 Apps" href="http://www.codingexplorer.com/supporting-dynamic-type-for-ios7-apps/">Supporting Dynamic Type for iOS7 Apps</a>, and <a title="Updating an app when returning from background in iOS" href="http://www.codingexplorer.com/updating-an-app-when-returning-from-background-in-ios/">Updating an app when returning from background in iOS</a>.&#8221;  You would be right, but in both of those, I talked about subscribing to them, but not generating them yourself.</p>
<p>In the case of the app I am working on, I needed this to be implemented in a class that handled the storing of settings, so during this post, I will refer to the class that will send notifications as the SettingsModel.</p>
<h2>Creating an NSNotificationCenter string constant</h2>
<p>If you look in my post about updating an app when returning from background, it has to subscribe to a notification by name, in that case UIApplicationWillEnterForegroundNotification.  We need to get read to do the same, so in your SettingsModel.h, you should add the line:</p>
<pre lang="objc">extern NSString* const SettingsModelChangedNotification;</pre>
<p>Then of course you have to actually set it up in your implementation file, so in SettingsModel.m, you add:</p>
<pre lang="objc">NSString* const SettingsModelChangedNotification = @"MyApp-SettingsModelChanged";</pre>
<p>It does not really matter what you write as the text in the NSString, other than that it should be unique, at least among the Notification keys, so that people can just subscribe to the specific notification that they want.</p>
<p>I actually have not used extern much myself, so I had to look up a bit about it and do some testing to accurately explain it.  I found a lot of the information I needed from this article:  <a title="Understanding &quot;extern&quot; keyword in C | GeeksforGeeks" href="http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/">Understanding “extern” keyword in C</a>, it even has examples!</p>
<p>When I deleted the &#8220;extern&#8221; from my class, it showed an error, &#8220;Cannot declare variable inside @interface or @protocol&#8221;.  Going to that article I linked to, this has to do with the difference between declaration and definition.  In a header file, you can only declare a variable.  You can make a readonly property, but in this case, that seems like a lot of overhead for a simple string constant.  The extern here declares that there WILL be an NSString named SettingsModelChangedNotification, and allows anything that includes SettingsModel.h to see it, but it will be defined elsewhere.  The logical place is simply in SettingsModel.m, and that&#8217;s what we do.  You declare its name in the header file, which you are allowed to do, but you don&#8217;t give it a value and memory to reside in until you define it, in your implementation file.</p>
<h2>Posting an NSNotification</h2>
<p>Okay, here comes the hard part.  Now that we have given it a name, now we have to actually send out this notification to the ether, and hope some other class hears it.  We will do this in your SettingsModel.m implementation file:</p>
<pre lang="objc">[[NSNotificationCenter defaultCenter] postNotificationName:SettingsModelChangedNotification object:self];</pre>
<p>Phew, I&#8217;m glad that&#8217;s over.  I know it was arduous, but we got through it.</p>
<p>Kidding aside, that&#8217;s pretty much all there is to it.  There seems to be more fuss about actually subscribing to it than actually making it.  All we are doing it first getting the NotificationCenter singleton provided by Apple, and then sending it a message to post the notification.  The &#8220;object&#8221; parameter is referring to the object that posted the notification.</p>
<p>Now, I don&#8217;t know about you, but I kind of find that statement kind of messy.  I mean, isn&#8217;t the object posting the notification ALWAYS going to be self?  Maybe not, but in my app, it is, so I made a little helper method to make this a bit prettier.</p>
<pre lang="objc">- (void)postChangedNotification:(NSString *)notificationName
{
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:self];
}</pre>
<p>So now, wherever I want to post a notification I can just use this one small line:</p>
<pre lang="objc">[self postChangedNotification:SettingsModelChangedNotification];</pre>
<p>Still a little long, but now I don&#8217;t have to keep asking explicitly for the NSNotificationCenter singleton, nor repeatedly say that it is self that posted it.</p>
<h2>Why the extra Notification Parameter?</h2>
<p>In the first version of my app, i actually had it even shorter.  It didn&#8217;t take ANY parameters, and just sent out the SettingsModelChangedNotification.  Now if you want all classes to be aware that something changed, that&#8217;s fine.  However, what if you had say, 3 properties (myInt1, myString2, and myObject3) and 2 classes (myClassA and myClassB).  Lets say myClassA wants to know if myInt1 or myString2 has changed, but doesn&#8217;t care about myObject3.  Additionally, you myClassB only cares about myObject3.</p>
<p>You could post a general SettingsModelChangedNotification, but if myObject3 changed, and myClassA hears about it, what should it do?  It will just waste time doing what it needs to do for myInt1 and myString2, even though they may not have changed.  You could make multiple notifications, and we just announce SettingsModel<strong>First</strong>GroupChangedNotification for myInt1 and myString2 changes, and then have SettingsModel<strong>Other</strong>GroupChangedNotification for myObject3.  Then myClassA only subscribes to SettingsModel<strong>First</strong>GroupChangedNotification, and myClassB only subscribes to SettingsModel<strong>Other</strong>GroupChangedNotification.</p>
<h2>Conclusion</h2>
<p>Since I have repeated it twice, I probably shouldn&#8217;t a third time, so if you want to see how to subscribe and use NSNotificationCenter properly, see my previous posts:  <a title="Supporting Dynamic Type for iOS7 Apps" href="http://www.codingexplorer.com/supporting-dynamic-type-for-ios7-apps/">Supporting Dynamic Type for iOS7 Apps</a>, and <a title="Updating an app when returning from background in iOS" href="http://www.codingexplorer.com/updating-an-app-when-returning-from-background-in-ios/">Updating an app when returning from background in iOS</a>.  This a very nice way to tell other classes when some event has occurred in your SettingsModel, or whatever class you want.  If you are just watching for variable changes, there is something else called Key-Value-Observing, but I still have not learned this, but will probably do so in the future, especially</p>
<p>Thank you very much to Matthijs Hollemans and his post <a title="Making Your Classes Talk to Each Other, Part 3 - The blog of Matthijs Hollemans" href="http://www.hollance.com/2011/04/making-your-classes-talk-to-each-other-part-3/">Making Your Classes Talk to Each Other, Part 3</a>.  I learned a lot about how to do this from his posts.</p>
<p>I hope this was helpful for using NSNotificationCenter in your apps.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.</p>
<p>Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/getting-started-with-nsnotificationcenter/">Getting started with NSNotificationCenter</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>WWDC 2014 Reactions and the Swift direction of this Blog</title>
		<link>https://www.codingexplorer.com/wwdc-2014-reactions-and-the-swift-direction-of-this-blog/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 05 Jun 2014 06:26:35 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=188</guid>

					<description><![CDATA[<p>So, to be perfectly honest, I was not expecting anything groundbreaking at this years WWDC.  I thought there would be iOS 8, which would have a few new features, but not TOO much.  I mean, after iOS 7, there should definitely be some cool-down time before anymore big changes to the OS.  I also thought [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/wwdc-2014-reactions-and-the-swift-direction-of-this-blog/">WWDC 2014 Reactions and the Swift direction of this Blog</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So, to be perfectly honest, I was not expecting anything groundbreaking at this years WWDC.  I thought there would be iOS 8, which would have a few new features, but not TOO much.  I mean, after iOS 7, there should definitely be some cool-down time before anymore big changes to the OS.  I also thought they would probably talk about OSX 10.10, and there would be a few new features too.  Not that I was expecting Apple to be lazy this year, but you can&#8217;t make something groundbreaking and amazing every single year.</p>
<p><span id="more-188"></span></p>
<h2>Swift</h2>
<p>With that being said, despite John Siracusa&#8217;s requests, I NEVER thought they would release a new programming language this year.  Maybe sometime in the next few years, but not 2014. I am definitely a fan of C#, and to a lesser extent Java, with how they handle some programming tasks.  So when I saw the screen showing off the new capabilities of Swift at WWDC, I was overjoyed.  Namespaces, Generics, Type Inference, and Multiple return types?  Yes, please!  I have already been going through <a title="iTunes - Books - The Swift Programming Language by Apple Inc." href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11">The Swift Programming Language Reference</a> book on the iBook Store, and am LOVING the new syntax.</p>
<p>So, guess what I&#8217;m going to do with this blog now?  I am currently not sure how much I can talk about besides what the Keynote said, but once allowed to, I am definitely planning on talking a lot about Swift on this blog.  I am currently not sure if it will be a whole leap to Swift only, or if there will still be a mix of Objective-C and Swift, but I am currently thinking that latter, but with Swift being the primary focus.  Either way though, I am blogging here to share what I learn in the hopes that it helps others learning as well, so if I learn something new in Objective-C, I will probably cover it here at some point.  When talking about Objective-C, I tend to talk about C related subjects that give a better view of that aspect of Objective-C, so I anticipate continuing to do that, to help describe something in Swift.</p>
<p>I am really looking forward to programming for iOS with Swift, and want to make this blog a helpful resource for those wanting to do the same.  Until then though, I still have been learning a lot about Objective-C and will continue to share such.</p>
<h2>OS X Yosemite</h2>
<p>I definitely see the effects of iOS7&#8217;s design on OS X Yosemite.  The iconography is a lot simpler, and their use of translucency in scrollviews to give you a &#8220;sense of place&#8221; as Apple says, which is particularly apropos in the &#8220;Maps&#8221; app, is definitely related to iOS 7.  The changes to Spotlight to show Wikipedia and other sources more easily is pretty nice too, as well as its integration with maps and iTunes.</p>
<p>The advent of Notification Center widgets is also very nice.  I have used the dashboard in the current version of OS X, I definitely think having many of the widgets from there, and more in the future, in the Notification Center makes them even easier to use.  I have never particularly been a fan of shifting my entire screen over just to check the whether really quick.  While the Notification Center does shift the screen a little, it doesn&#8217;t completely replace it like Dashboard does.</p>
<h3>Phone and SMS Forwarding</h3>
<p>I am not the biggest user of SMS, but I definitely think it is a good thing to have it integrated with Messages.  I love using it to communicate between my friends and family that have Apple devices, and have definitely felt that it would be nice to have what SMS&#8217;s I do use in here, to be able text communicate from everywhere.  On the other hand though, Phone forwarding, that is absolutely awesome.  I liked doing FaceTime with the mac to other Apple devices, but being able to use my phone while sitting at my computer and not having to hold it up to my ear or switch out my headphones for a headset for the phone while be very helpful.  The instant hotspot looks cool too, though I doubt it will let those of us that don&#8217;t have tethering on our plans, and can&#8217;t (with the older iPhone Unlimited data plan).  I will update here when I find out whether that is the case.</p>
<h3>iCloud Drive</h3>
<p>This definitely looks cool to me.  Obviously there are plenty of other cloud storage media that I have used, but having one directly built into all of my Apple devices makes it just plain easy.  Its integration with Handoff makes it even better, so you can work on whatever device you want, whenever you want, without so much as a &#8220;send to my other device&#8221; command.</p>
<h2>iOS 8</h2>
<p>There were a few updates to iOS 8 as well, which were cool, but definitely not as groundbreaking as iOS 7.</p>
<h3>Photos</h3>
<p>I have not really been the biggest fan of Photo Streams, so I might not be the best person to ask about this, but if iCloud Photo Library is better than such, I could see it as being quite useful.  I am one of the few people that likes plugging my phone in to charge, and organizing my photos into my own repository and syncing them back via iPhoto, but if it integrates with that, I might take them up on this one.  We shall see.</p>
<p>The improved built-in photo-editting capabilities are good, and I might use them a bit, but the extensions to work with other apps to edit photos, that is the really good addition to this app.</p>
<p>There is one addition to the Photos app that, I don&#8217;t believe was in the Keynote, but I find quite cool, and something I might use if I can put my phone down long enough to do so:  Time-lapse videos.  It does basically what it sounds like.  You set your phone up somewhere, apparently set the time interval, and it creates a movie of photos taken at these intervals.  Pretty neat.</p>
<h3>Messages &#8211; Voice, video, and location messages</h3>
<p>This is interesting.  I thought text was sufficient for messages, but adding short clips to replies, I could see myself using it.  I almost feel like I won&#8217;t use it, but then find myself in a couple months using it all the time.</p>
<h3>Family Sharing</h3>
<p>I think this is my favorite capability of iOS 8.  It&#8217;s major capability:  to allow you to share your iTunes, iBooks, and App store purchases between family members.  I think I will use this one all the time.  So now, if I want to play a game with somebody in my family, they can just download it from my App Store account, and we don&#8217;t have to buy a second copy, if it is paid.  Family sharing also gives access to a shared photo album.  It is basically a photo stream like I had mentioned I&#8217;m not a big fan of before&#8230; but one automatically set up for my family, I think I may actually start using it.  Organizing family calendars will be very helpful as well, so that it will be easy to tell when things are happening for myself, my wife, and my child (when he&#8217;s old enough to use this), in one view.  I currently do this somewhat via Google Calendar, but still, having this automatically set up for my family once I add family members to my iCloud account, is quite nice.  Being able to see the location of my family&#8217;s devices I&#8217;m sure will be useful in the future.</p>
<p>And of course, especially with a child with an iDevice, the &#8220;Ask to Buy&#8221; feature.  With it, a user that tries to buy something on the app store that is not allowed to authorize payments, will send a request to the parent&#8217;s iDevice saying that the child (or whoever) is trying to buy something, and ask you for your permission.  I think this will be VERY useful in my future.</p>
<h3>Health</h3>
<p>This one, I think has good potential, and if it lives up to it, will be quite useful.  I currently use a few different apps to track my health on the iPhone, including <a title="Calorie Counter &amp;amp; Diet Tracker by MyFitnessPal on the App Store on iTunes" href="https://itunes.apple.com/us/app/calorie-counter-diet-tracker/id341232718?mt=8">MyFitnessPal</a>, <a title="RunKeeper - GPS Running, Walk, Cycling, Workout and Weight Tracker on the App Store on iTunes" href="https://itunes.apple.com/us/app/runkeeper-gps-running-walk/id300235330?mt=8">RunKeeper</a>, and <a title="Pedometer++ on the App Store on iTunes" href="https://itunes.apple.com/us/app/pedometer++/id712286167?mt=8">Pedometer++</a>.  Having them all report to a central repository could be a good thing.  I think they are currently fine separate (though currently RunKeeper already talks to MyFitnessPal, so they aren&#8217;t entirely separate), but I will definitely be watching this to see how it goes.</p>
<h2>Conclusion</h2>
<p>I know this post is not really going into any nitty-gritty programming, but talking about the news of  Swift and WWDC I believe is a good reason change it up a bit.  I may have rambled a bit for my reviews of general parts of OS X Yosemite and iOS 8, but I felt it would be useful to list off a bunch of my personal highlights about the new features in one place.  A lot of my commentary was saying how &#8220;nice&#8221; or &#8220;awesome&#8221; something new is, but a lot of it was giving a quick overview of the some details of these new capabilities.</p>
<p>Anyway, for the future of this blog, if you have any suggestions of what to talk about in Swift or even Objective-C, you can message me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and we&#8217;ll see what we can do about putting that topic into the hopper.  I will be chronicling what I learn, but if you have things you all want to know, I can steer my learning that way a bit and help explain it as well.  Thank you for reading this post, and I hope you found it helpful.  Good luck on your new apps, and I hope I can be of help.</p>
<p>The post <a href="https://www.codingexplorer.com/wwdc-2014-reactions-and-the-swift-direction-of-this-blog/">WWDC 2014 Reactions and the Swift direction of this Blog</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Getting Started With NSNumberFormatter</title>
		<link>https://www.codingexplorer.com/getting-started-with-nsnumberformatter/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 14 May 2014 07:03:41 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=179</guid>

					<description><![CDATA[<p>So, you want to print out a floating point number.  Do you want it to as high of accuracy as your computer can muster?  In general, you probably don&#8217;t.  If I was splitting a $43.89 check 4 ways, would you really want to know that the answer is $10.9725?  Of course you could round the [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/getting-started-with-nsnumberformatter/">Getting Started With NSNumberFormatter</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So, you want to print out a floating point number.  Do you want it to as high of accuracy as your computer can muster?  In general, you probably don&#8217;t.  If I was splitting a $43.89 check 4 ways, would you really want to know that the answer is $10.9725?  Of course you could round the number yourself, but why, when you can simply use NSNumberFormatter!</p>
<p><span id="more-179"></span></p>
<h2>Formatting with Style!</h2>
<p>So, first things first, what kind of number do you want to work with.  Do you want currency like above, or maybe something else?  You will need to set your NSNumberFormatter object&#8217;s NumberStyle.  These are denoted by the aptly (or maybe Apple-tly?  I should remember that word) named NSNumberFormatterStyle enum.  The available options are&#8230;.</p>
<h3>NSNumberFormatterStyle</h3>
<ul>
<li>NSNumberFormatterNoStyle</li>
<li>NSNumberFormatterDecimalStyle</li>
<li>NSNumberFormatterCurrencyStyle</li>
<li>NSNumberFormatterPercentStyle</li>
<li>NSNumberFormatterScientificStyle</li>
<li>NSNumberFormatterSpellOutStyle</li>
</ul>
<p>So what do each of these do?</p>
<h3>NSNumberFormatterNoStyle</h3>
<p>This is by default, an integer formatter, with nothing special.  So a value of 24891318.58825 comes out as 24891319.  So it rounds appropriately, and then says the integer form of the number.</p>
<h3>NSNumberFormatterDecimalStyle</h3>
<p>This adds the appropriate separators and decimal points for your locale, and by default is limited to 3 decimal places, so 24891318.58825 comes out as 24,891,318.588 (in en-US locale).</p>
<h3>NSNumberFormatterCurrencyStyle</h3>
<p>This is similar to NSNumberFormatterDecimalStyle, but with the locale specific currency symbol, so 24891318.58825 comes out as $24,891,318.59 (in en-US locale).</p>
<h3>NSNumberFormatterPercentStyle</h3>
<p>This one I found a little surprising, but it assumes you already have your percentage in decimal form, so it expects your value of 39.2% to be in the form 0.392.  So if we continue with the same number, 24891318.58825 comes out as 2,489,131,859%.  Notice the magnitude of this one.  The previous answers were all 24 million 891 thousand, etc.  This one is 2.489 billion percent.  So by default it multiplies the value by 100, and outputs no decimal values.</p>
<h3>NSNumberFormatterScientificStyle</h3>
<p>This by default puts out the normalized scientific notation of the value.  It outputs it in E-Notation, instead of the classic a x 10^b style, but that is common enough in computers.  So 24891318.58825 comes out as 2.489131858825E7.</p>
<h3>NSNumberFormatterSpellOutStyle</h3>
<p>I did not know about this one until I started writing this.  This is kind of cool, it actually will write out your value into words.  It even will output it in the correct language for your locale!  So 24891318.58825 comes out as &#8220;twenty-four million eight hundred ninety-one thousand three hundred eighteen point five eight eight two five&#8221; (in en-US locale).</p>
<h2>How Many digits?</h2>
<p>You can also set how many digits.  The above styles have some built in settings for this, but they can be overridden.  You can set the minimum or maximum number of integer or fractional digits.  You just have to modify the appropriate  property in your NSNumberFormatter object.</p>
<p>These are:</p>
<ul>
<li>minimumIntegerDigits</li>
<li>maximumIntegerDigits</li>
<li>minimumFractionDigits</li>
<li>maximumFractionDigits</li>
</ul>
<p>Since these are properties, you can either do this through dot syntax, or the appropriate setter in normal message syntax:</p>
<pre lang="objc">//Dot Syntax
yournumberformatter.maximumFractionDigits = 3;

//Message syntax
[yourNumberFormatter setMaximumFractionDigits: 3];
</pre>
<h2>Actually Using NSNumberFormatter</h2>
<p>So, how do you actually use this?  Lets just use one of the built in formats above for simplicity:</p>
<pre lang="objc">NSNumber *myNumber = @(24891318.58825);
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
nf.numberStyle = NSNumberFormatterDecimalStyle;
NSLog(@"NSNumberFormatterDecimalStyle - %@", [nf stringFromNumber:myNumber]);
</pre>
<p>That&#8217;s it!  All you do is ask the NSNumberFormatter object for a string based off of your NSNumber, and it gives you the appropriate string based off of the settings you give it (in this case, the NSNumberFormatterDecimalStyle).</p>
<h2>Conclusion</h2>
<p>I have only scratched the surface of what NSNumberFormatter can do.  Among other notable capabilities, it can actually read a string and give you an NSNumber back from it, but I&#8217;ll leave that to another post.</p>
<p>I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/getting-started-with-nsnumberformatter/">Getting Started With NSNumberFormatter</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Add sharing to your app via UIActivityViewController</title>
		<link>https://www.codingexplorer.com/add-sharing-to-your-app-via-uiactivityviewcontroller/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 04 Apr 2014 15:18:52 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=170</guid>

					<description><![CDATA[<p>Ever wonder what various apps like Photos or Safari use when you click on the share button? So did I until a few days ago. It is apparently UIActivityViewController. I just learned a bit about how to use it, so I thought I would pass it along. Update November 10, 2014:  Want to see how [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/add-sharing-to-your-app-via-uiactivityviewcontroller/">Add sharing to your app via UIActivityViewController</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Ever wonder what various apps like Photos or Safari use when you click on the share button? So did I until a few days ago. It is apparently UIActivityViewController. I just learned a bit about how to use it, so I thought I would pass it along.</p>
<p><strong>Update November 10, 2014:</strong>  Want to see how to use UIActivityViewController in Swift?  Check out the my newer post <a title="Add sharing to your Swift app via UIActivityViewController" href="http://www.codingexplorer.com/sharing-swift-app-uiactivityviewcontroller/">Add sharing to your Swift app via UIActivityViewController</a><span id="more-170"></span></p>
<h2>Setting the Icon</h2>
<p>While not a HUGE step, I thought I might mention it anyway. For my app, I wanted to use the standard Apple sharing button (which in iOS7 is a box with an arrow pointing up from the center). To get it from Interface Builder, you must use a UIBarButtonItem, so this button can only be in a UINavigationBar (part of UINavigationController) or UIToolbar.  You simply add a UIBarButtonItem, and change its &#8220;Identifier&#8221; in the Attributes Inspector to &#8220;Action, as shown in the image.</p>
<div id="attachment_172" style="width: 270px" class="wp-caption aligncenter"><a href="http://www.codingexplorer.com/wp-content/uploads/2014/04/SharingAttributes.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-172" class="size-full wp-image-172" src="http://www.codingexplorer.com/wp-content/uploads/2014/04/SharingAttributes.png" alt="Bar Button Item Attributes Inspector with &quot;Identifier&quot; set to &quot;Action&quot;" width="260" height="124" /></a><p id="caption-attachment-172" class="wp-caption-text">The Identifier is set to Action for the sharing icon.</p></div>
<h2>Now the Code</h2>
<p>This is actually surprisingly easy to do.  So wire that up to an IBAction, here is the gist of how mine was set up.</p>
<pre lang="objc">- (IBAction)shareButton:(UIBarButtonItem *)sender
{
    NSString *textToShare = @"Look at this awesome website for aspiring iOS Developers!";
    NSURL *myWebsite = [NSURL URLWithString:@"http://www.codingexplorer.com/"];

    NSArray *objectsToShare = @[textToShare, myWebsite];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];

    NSArray *excludeActivities = @[UIActivityTypeAirDrop,
                                   UIActivityTypePrint,
                                   UIActivityTypeAssignToContact,
                                   UIActivityTypeSaveToCameraRoll,
                                   UIActivityTypeAddToReadingList,
                                   UIActivityTypePostToFlickr,
                                   UIActivityTypePostToVimeo];

    activityVC.excludedActivityTypes = excludeActivities;

    [self presentViewController:activityVC animated:YES completion:nil];
}</pre>
<p>That&#8217;s about it.  You make an NSArray of objects to share, and basically pass that along to the UIActivityViewController when you instantiate it.  For my app, I just wanted an NSString, and an NSURL to be shared, so I excluded things where that would make less sense like Printing, AirDropping, Vimeo, etc.  You can read more about this at the Apple <a title="UIActivity Class Reference" href="https://developer.apple.com/library/ios/documentation/uikit/reference/UIActivity_Class/Reference/Reference.html">UIActivity Class Reference</a>.  Currently it supports these UIActivityTypes:</p>
<ul>
<li>UIActivityTypePostToFacebook</li>
<li>UIActivityTypePostToTwitter</li>
<li>UIActivityTypePostToWeibo</li>
<li>UIActivityTypeMessage</li>
<li>UIActivityTypeMail</li>
<li>UIActivityTypePrint</li>
<li>UIActivityTypeCopyToPasteboard</li>
<li>UIActivityTypeAssignToContact</li>
<li>UIActivityTypeSaveToCameraRoll</li>
<li>UIActivityTypeAddToReadingList</li>
<li>UIActivityTypePostToFlickr</li>
<li>UIActivityTypePostToVimeo</li>
<li>UIActivityTypePostToTencentWeibo</li>
<li>UIActivityTypeAirDrop</li>
</ul>
<p>So for my app, I left it able to post to Facebook, Twitter, Weibo, Tencent Weibo, Message, Mail, and copy to the Pasteboard.</p>
<p>Anyway, you then set that to the excludedActivityTypes property, and then tell your current view controller to present the UIActivityViewController.  I was very surprised at how easy this was.  So when you click on Facebook or Twitter in the UIActivityViewController (as long as you are set up to use Twitter or Facebook), it will show your text, and attach the URL in whatever way is appropriate for that social media choice.  If you use Message or copy it to the pasteboard, you should get something similar to &#8220;Look at this awesome website for aspiring iOS Developers! http://www.codingexplorer.com/ &#8220;.</p>
<p>I will probably update this post as I learn more about UIActivityViewController.  I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<h2>Sources:</h2>
<p>This post was heavily influenced by a great tutorial for using AirDrop from the AppCoda Blog at <a title="iOS Programming Tutorial: Adding AirDrop File Sharing in Your Apps" href="http://www.appcoda.com/ios7-airdrop-programming-tutorial/">http://www.appcoda.com/ios7-airdrop-programming-tutorial/</a> written by Simon Ng.  Thank you for the great tutorial.</p>
<p>The post <a href="https://www.codingexplorer.com/add-sharing-to-your-app-via-uiactivityviewcontroller/">Add sharing to your app via UIActivityViewController</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Using UILocalNotification</title>
		<link>https://www.codingexplorer.com/using-uilocalnotification/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Wed, 02 Apr 2014 16:00:00 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=163</guid>

					<description><![CDATA[<p>Have you ever wanted to have your app give a notification when it is not open, but don&#8217;t have a web backend?  That&#8217;s where UILocalNotification comes in. One caveat, UILocalNotification cannot open your app (at least as far as I know), so it can only run at pre-programmed times, but that is still useful in [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/using-uilocalnotification/">Using UILocalNotification</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Have you ever wanted to have your app give a notification when it is not open, but don&#8217;t have a web backend?  That&#8217;s where UILocalNotification comes in.</p>
<p>One caveat, UILocalNotification cannot open your app (at least as far as I know), so it can only run at pre-programmed times, but that is still useful in many situations.</p>
<h2>An example use of UILocalNotification</h2>
<p>UILocalNotification is pretty simple to setup in the simplest cases.  Below is an example of one I used:<br />
<span id="more-163"></span></p>
<pre lang="objc">- (void) createMyNotifications
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    comps.day = 31;
    comps.month = 12;
    comps.year = 2013;
    NSDate * nextAlertTime = [[NSCalendar currentCalendar] dateFromComponents:comps];

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = nextAlertTime;
    notification.timeZone = [NSTimeZone systemTimeZone];
    notification.alertBody = nil;
    notification.soundName = nil;
    notification.applicationIconBadgeNumber = 28;

    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}</pre>
<p>So let&#8217;s unpack this.  First off, just in case my program still had some notifications left in the buffer that I now want to invalidate, I use [[UIApplication sharedApplication] cancelAllLocalNotifications] .  That is just a message to my application itself to cancel its notifications.</p>
<p>After that, I need a date to tell the alert when to happen.  If you recognize that code, you should, because it is taken pretty much directly from my post <a title="Displaying a human readable NSDate" href="http://www.codingexplorer.com/displaying-a-human-readable-nsdate/">&#8220;Displaying a human readable NSDate&#8221;</a>, with a changed name for the NSDate object.</p>
<p>Next we create the UILocalNotification.  Nothing special needs to be done at this step, so just use a vanilla [[alloc] init].</p>
<p>Now things get interesting.  First we set the notification&#8217;s &#8220;fireDate&#8221; property to that NSDate we made earlier.  After that, we have to set the &#8220;timeZone&#8221; property to denote what timeZone that NSDate was set in. This is a bit confusing to me, and I might change this in my app soon, but according to the <a title="UILocalNotification Class Reference" href="https://developer.apple.com/library/ios/documentation/iPhone/Reference/UILocalNotification_Class/Reference/Reference.html#jumpTo_12">apple documentation for the timeZone property</a>:</p>
<blockquote><p>The date specified in <code><a href="https://developer.apple.com/library/ios/documentation/iPhone/Reference/UILocalNotification_Class/Reference/Reference.html#//apple_ref/occ/instp/UILocalNotification/fireDate">fireDate</a></code> is interpreted according to the value of this property. If you specify <code>nil</code> (the default), the fire date is interpreted as an absolute GMT time, which is suitable for cases such as countdown timers. If you assign a valid <code><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSTimeZone_Class/Reference/Reference.html#//apple_ref/occ/cl/NSTimeZone" target="_self">NSTimeZone</a></code> object to this property, the fire date is interpreted as a wall-clock time that is automatically adjusted when there are changes in time zones; an example suitable for this case is an an alarm clock.</p></blockquote>
<p>So, since my program is actually a countdown timer, I should probably change this to nil for my program.  If yours is more like an alarm clock, you should probably set the appropriate timezone it was set in.</p>
<p>Next we start setting what we want the user to see.  In this case, I just want to update the application badge number, so I set the other two things to nil.  So in this case, to set the badge, we just set the applicationIconBadgeNumber property.  Now there other two are useful in other situations.  The &#8220;alertBody&#8221; takes an NSString, and this is what is printed in the notification.  This I believe shows up in the Notification center, as well as the text that you show as the notification in the banner or alert view, whichever the user has set in their notification center preferences in the Settings app.</p>
<p>The soundName property is where you could tell it to play a sound when this UILocalNotification is triggered.  The default should be nil (no sound), but I wanted to make it obvious that such was my intent.  You could use the default chime sound with UILocalNotificationDefaultSoundName.  If you have your own, and it is included in the bundle, you can just put its name in there with extension, like @&#8221;someSound.mp3&#8243;.</p>
<p>Finally, we have finished constructing our notification, and now we simply schedule it with [[UIApplication sharedApplication] scheduleLocalNotification:notification].  Pretty simple.</p>
<h2>A note about applicationIconBadgeNumber</h2>
<p>As mentioned earlier, this cannot wake up your app, at least that I know, so you have to preprogram things.  So say you wanted to game, and you wanted to notify the user that there are 5 things to attend to in your app that are added on some interval, like every 2 hours.  In this case, you would have to set up 5 different notifications, each with their NSDates 2 hours apart, and set the notifications manually to whatever badge number you wanted.  It would be nice if it could wake up the app and do some processing if needed, but currently it cannot.  Push notifications can, and if we work more with the Background Modes added in iOS7 we might, but I have not worked with either of these yet.</p>
<p>I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/using-uilocalnotification/">Using UILocalNotification</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Introduction to UIColor</title>
		<link>https://www.codingexplorer.com/introduction-to-uicolor/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 01 Apr 2014 01:30:40 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=138</guid>

					<description><![CDATA[<p>For an app I am working on, I wanted to use some specific colors outside of the standard system ones.  Using UIColor is pretty easy, but I thought I would share with you how to use it in its simplest form, and a help category I made to make working with the built in functions [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/introduction-to-uicolor/">Introduction to UIColor</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="line-height: 1.5em;">For an app I am working on, I wanted to use some specific colors outside of the standard system ones.  Using UIColor is pretty easy, but I thought I would share with you how to use it in its simplest form, and a help category I made to make working with the built in functions a bit easier, and a tool I JUST found while working on this post that would have been very nice last week.  If you want to learn how to make a category, see my previous post <a title="Objective-C Categories" href="http://www.codingexplorer.com/objective-c-categories/">Objective-C Categories</a>.</span></p>
<h1>Creating a UIColor Object</h1>
<p>UIColor has several methods to generate a color based off of components.  The available ones are:</p>
<ul>
<li>colorWithWhite:alpha:</li>
<li>colorWithHue:Saturation:brightness:alpha:</li>
<li>colorWithRed:green:blue:alpha:</li>
<li>colorWithCGColor:</li>
<li>colorWithPatternImage:</li>
<li>colorWithCIColor:</li>
</ul>
<p>But we are going to work with <strong>colorWithRed:green:blue:alpha:</strong> in this post.</p>
<p>Also, each of those has an init form (so colorWithRed:green:blue:alpha: is initWithRed:green:blue:alpha: ).  This makes less difference in a post ARC world, but for reference, the initWith forms give your class ownership of the object, and so it must be released when you are done with it to avoid memory leaks.  The colorWith form (also called a &#8220;Factory Method&#8221;), does not give your class ownership, so it does not need to be released by your class, that is handled by the system.  Since ARC automatically counts your references, they are effectively the same for the programmer nowadays.</p>
<h1><span id="more-138"></span>[UIColor colorWithRed:green:blue:alpha: ]</h1>
<p>I feel that this is the easiest way to generate a UIColor, all you need is the RGB values, that you can get from any image editor.  One hitch to me though, is that RGB values are usually given as an integer between 0 and 255.  This method though, only takes CGFloat values between 0.0 and 1.0.  Nothing difficult, it just is the percentage value, so a Red value of 204 would be 204/255 = 0.8.</p>
<p>But I didn&#8217;t want to have to do that calculation myself every time I wanted to put in a color, so I made a category for UIColor to add a helper method to take those numbers directly.  I have simplified it a bit here and taken out some bound-checking for clarity, but that should probably be added for production code:</p>
<pre class="lang:swift decode:true ">+ (UIColor *)colorWithRed:(NSInteger)inputRed Green:(NSInteger)inputGreen Blue:(NSInteger)inputBlue
{
    CGFloat newRed = inputRed/255.0;
    CGFloat newGreen = inputGreen/255.0;
    CGFloat newBlue = inputBlue/255.0;
    
    return [UIColor colorWithRed:newRed green:newGreen blue:newBlue alpha:1.0];
}</pre>
<p>So it takes in NSInteger values of red, green and blue, then divides them by 255.0.  I divide it with the &#8220;.0&#8221; on it to force it to be interpreted as a floating point value, and this will generate floating point values that can be placed into CGFloat variables.  I then create the color, and hard code the alpha to 1.0.  The alpha controls the opacity of the color, so anything less than 1.0 is partially transparent.  With nothing behind what I was coloring, it just made the colors darker (mixing it with the black  of the nothingness behind it).  I just simply hardcoded the value to 1.0 for my helper method because I just want this method to make fully-opaque colors, and don&#8217;t want to type that alpha value every time.</p>
<p>In my version, there is a bit more work to verify that the numbers are capped at 0 and 255, so if something lower or higher is set, they will simply be set to the appropriate bound (so a value of 300 would come out as 255).  So in a real version, you should probably add that, but this gives you the important part of dealing with UIColor.</p>
<h1>What is CGFloat?</h1>
<p>One interesting side not about this, CGFLoat is basically a float that is appropriate for the system, like NSInteger.  If you click in to its definition, you see this:</p>
<pre lang="objc">typedef CGFLOAT_TYPE CGFloat;
#define CGFLOAT_DEFINED 1</pre>
<p>Okay, nothing too special there, but you do see that the typdef sets whatever CGFLOAT_TYPE to be referred to as CGFloat.  I am not sure where CGFLOAT_DEFINED is use though.  Anyway, so what is CGFLOAT_TYPE?  Well, if you look right above it&#8230;</p>
<pre lang="objc">#if defined(__LP64__) &amp;&amp; __LP64__
# define CGFLOAT_TYPE double
# define CGFLOAT_IS_DOUBLE 1
# define CGFLOAT_MIN DBL_MIN
# define CGFLOAT_MAX DBL_MAX
#else
# define CGFLOAT_TYPE float
# define CGFLOAT_IS_DOUBLE 0
# define CGFLOAT_MIN FLT_MIN
# define CGFLOAT_MAX FLT_MAX
#endif</pre>
<p>The if statement is checking if you are on a 64-bit system, like the iPhone 5s.  If it is, CGFLoat is defined as a double, sets CGFLOAT_IS_DOUBLE to let you check that if you want, and sets the min and max for CGFloat to the min and max of a double.  If you aren&#8217;t on a 64-bit system, then all of that is set to the appropriate float values.</p>
<p>Too geeky?  Maybe, but I thought it was cool.</p>
<h1>The tool I found:  uicolor.org</h1>
<p>So, when I was starting to look up some references to help me, I found <a title="UIcolor Code Generator" href="http://uicolor.org/">http://uicolor.org/</a> .  It is a very simple website, but it gets the job done.  It shows a color picker, and you can just select an area of that, it will show your the RGB values (or the Hue, Saturation, and Brightness, if you like that sort of thing), and it even generates the Objective C code to generate the color directly!  So, for a nice forest green color I found in the color picker, it generated this command for me:</p>
<pre lang="objc">UIColor * color = [UIColor colorWithRed:113/255.0f green:175/255.0f blue:109/255.0f alpha:1.0f];</pre>
<p>Pretty cool, eh?</p>
<p>Although one small note, below the text box to copy it, it says to press Ctrl+C to copy.  Unless you changed your keybindings, or are doing the text on a Windows machine for some reason, you will have to use Cmd+C.</p>
<p>I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps.  Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/introduction-to-uicolor/">Introduction to UIColor</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Displaying a human readable NSDate</title>
		<link>https://www.codingexplorer.com/displaying-a-human-readable-nsdate/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 28 Mar 2014 23:39:10 +0000</pubDate>
				<category><![CDATA[Syntax]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=129</guid>

					<description><![CDATA[<p>Much like Casey Liss of the Accidental Tech Podcast, talked about recently on the Debug podcast, I came from C# before I started working on Objective-C.  One frustration he had originally with Objective-C was with getting a human readable date out of an NSDate object, when it was so easy to just type someDateTime.toString() in C#. [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/displaying-a-human-readable-nsdate/">Displaying a human readable NSDate</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Much like <a title="Casey Liss (caseyliss) on Twitter" href="https://twitter.com/caseyliss">Casey Liss</a> of the <a title="Accidental Tech Podcast" href="http://atp.fm/">Accidental Tech Podcast</a>, talked about recently on the <a title="Debug 30: Casey Liss on C# and .Net | iMore" href="http://www.imore.com/debug-30-casey-liss-c-and-net">Debug podcast</a>, I came from C# before I started working on Objective-C.  One frustration he had originally with Objective-C was with getting a human readable date out of an NSDate object, when it was so easy to just type someDateTime.toString() in C#.  That was also one of my earliest frustrations, and I thought it would be nice to share with my readers.</p>
<p>In C#, you store dates in objects of the type DateTime.  The Objective-C equivalent of this is NSDate.  In C#, you can simply create a specific date date with:</p>
<pre lang="csharp">DateTime someDate = new DateTime(2013, 12, 31);</pre>
<p>And that would make a DateTime object for December 31, 2013.  There are a few ways to do this in Objective-C, and while they are not as easy, they do make it much more friendly to using non-Gregorian calendar systems.  NSDateFormatter can both format an NSDate into a string (more on this later), but it can also attempt to parse a string with date data.  The more exact way though, would probably be to use NSDateComponents.</p>
<p><span id="more-129"></span>To make a similar NSDate, you would do it thusly:</p>
<pre lang="objc">NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = 31;
comps.month = 12;
comps.year = 2013;
NSDate *someDate = [[NSCalendar currentCalendar] dateFromComponents:comps];</pre>
<p>Much more verbose, but it gets the job done.  I basically request the NSCalendar object, to make a date (in that calendar style), that has 12 months, 31 days, and 2013 years as its components.  NSCalendar currentCalendar is requesting an instance of the calendar system chosen in the device&#8217;s system preferences.  Now, to actually print this out in a human readable way, you use the earlier mentioned NSDateFormatter.  There are several built in styles of formatting the date, and you can also specify your own.</p>
<p>Here are the built in ones (with the exception of NSDateFormatterNoStyle, whose reason for not being included should be self-explanatory).  These can instruct the NSDateFormatter to format a date (when used as a dateStyle), and to format time (when used as a timeStyle).  These have the added benefit of adapting to the current user&#8217;s locale.  The examples shown below are for an en-US locale.</p>
<table border="1&quot;">
<tbody>
<tr>
<th style="text-align: left;">NSDateFormatterStyle</th>
<th style="text-align: left;">Date Out</th>
<th style="text-align: left;">Time Out</th>
</tr>
<tr>
<td>NSDateFormatterShortStyle</td>
<td>12/31/13</td>
<td>2:15 PM</td>
</tr>
<tr>
<td>NSDateFormatterMediumStyle</td>
<td>Dec 31, 2013</td>
<td>2:15:09 PM</td>
</tr>
<tr>
<td>NSDateFormatterLongStyle</td>
<td>December 31, 2013</td>
<td>2:15:09 PM PST</td>
</tr>
<tr>
<td>NSDateFormatterFullStyle</td>
<td>Tuesday, December 31, 2013 AD</td>
<td>2:15:09 PM Pacific Standard Time</td>
</tr>
</tbody>
</table>
<p>So to use these, you would use the code below:</p>
<pre lang="objc">NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterLongStyle;
self.someLabel.text = [formatter stringFromDate:someDate];</pre>
<p>If you want to make your own, you would not assign a dateStyle, and instead set a format string to the dateFormat property.  The full list of format patterns is available on this <a title="UTS #35: Unicode LDML: Dates" href="http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns">UnicodeTechnical Standard #35 page</a> (this is only valid for iOS7, different releases go to different standards).  The <a title="Data Formatting Guide: Date Formatters" href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW13">Apple documentation</a> shows a good example of using the a custom Date Format.</p>
<pre lang="objc">[formatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];</pre>
<p>Which would output something like &#8220;2013-12-31 at 08:45&#8221;, if I had set a time to my date.</p>
<p>It&#8217;s a small topic, but certainly a frustrating one when a person is starting out with the language.  I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps. Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.  Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/displaying-a-human-readable-nsdate/">Displaying a human readable NSDate</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Property Attributes in Objective-C</title>
		<link>https://www.codingexplorer.com/property-attributes-in-objective-c/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 04 Mar 2014 05:17:26 +0000</pubDate>
				<category><![CDATA[Syntax]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=126</guid>

					<description><![CDATA[<p>In my previous articles, you&#8217;ve probably seen properties used many times. In this article I wanted to write down (in one place) and explain the attributes that can be used on them. At least in this context, &#8220;attributes&#8221; refers to the modifiers to the property (usually strong and nonatomic in my previous articles). I have [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/property-attributes-in-objective-c/">Property Attributes in Objective-C</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="line-height: 1.5em;">In my previous articles, you&#8217;ve probably seen properties used many times. In this article I wanted to write down (in one place) and explain the attributes that can be used on them. At least in this context, &#8220;attributes&#8221; refers to the modifiers to the property (usually strong and nonatomic in my previous articles). I have covered those two a little bit in a previous article, but I wanted to list them all here.</span></p>
<h2> Valid Property Attributes</h2>
<ul>
<li>atomic</li>
<li>nonatomic</li>
<li>strong</li>
<li>weak</li>
<li>readwrite</li>
<li>readonly</li>
<li>getter=</li>
<li>setter=</li>
<li>copy</li>
<li>assign</li>
<li>retain</li>
<li>unsafe_unretained</li>
</ul>
<h3><span id="more-126"></span>atomic</h3>
<p>Properties are atomic by default, so if you don&#8217;t write nonatomic, it will be atomic (whether you write it or not).  Atomic basically ensures that data is written or read atomically.  So if thread A is still in the getter when thread B calls the setter, thread A will get a viable value.  It is not necessarily thread-safe, but much safer than nonatomic.  The problem with atomic though, is that it is quite slow compared to its opposite.  Also, you must either implement both the setter and the getter, or neither. You cannot have a custom getter and a synthesized setter in an atomic property.</p>
<h3>nonatomic</h3>
<p>This makes no such guarantees about atomicity (which is quite a cool word) as nonatomic.  If thread A is in the middle of a getter for a nonatomic NSString, and Thread B tries to set it to &#8220;Microwave&#8221;, and Thread C tries to set it to &#8220;Refrigerator&#8221;, you might get &#8220;Microgerator&#8221;, or it may just be completely unreadable and crash the program.  You never know, so if you use nonatomic, you must implement your own thread safety and atomicity.  You will more often use nonatomic properties though, because they are FAST when compared to atomic ones.</p>
<h3>strong</h3>
<p>This is also a default attribute, and must be overridden if you want to change it.  In ARC, its opposite is the &#8220;weak&#8221; attribute.  I started post-ARC, so my first-hand knowledge is better with strong and weak, compared to the pre-ARC ones listed later.  Strong is generally used by a class to establish ownership of an object.  It increases the retain count (something ARC deals with for you), it basically keeps the object that is pointed to in memory until that class instance stops pointing to it.  This is usually what you want, but there it can cause something called a &#8220;retain cycle.&#8221;  The weak attribute helps solve this issue.</p>
<h3>weak</h3>
<p>This gives a pointer to an object, but does not claim ownership, and does not increase the retain count.  It basically keeps a valid pointer to an object as long as another class points to it strongly.  If nothing else is trying to retain it, the weak pointer is automatically set to nil.  An example where this would be useful is if you had two classes, one for a petOwner, and one for their pet.  Lets say for some reason we want them to refer to each other, so you can request the pet of an owner, or an owner of a pet.  If the pet&#8217;s petOwner property, and the petOwner&#8217;s pet property were both strong, the memory could never be released because they would both be telling ARC that they both need it.  If we set the petOwner&#8217;s pet property to weak, then we avoid the retain cycle.  If the pet object is destroyed, while the petOwner still has a reference to it, the petOwner&#8217;s pet property will be automatically set to nil.</p>
<h3>readwrite</h3>
<p>This is a default attribute and it can be overridden by readonly.  This basically tells the compiler to generate both a getter and a setter (or an accessor and mutator if you want to use fancy language).</p>
<h3>readonly</h3>
<p>This can override readwrite.  It tells the compiler to only generate a getter for an object.  One common thing to do with these two, is if you want a property visible to another class, but not able to be changed by an external class, set the property to readonly in your header file, and in your implementation file ( .m file), declare it as readwrite.  That way your implementation has a getter and a setter, while external classes only get the getter.</p>
<h3>getter=</h3>
<p>This just gives a custom name for a getter.  The default getter is just the name of the property.  For instance for the UISwitch control in iOS, the property that says whether the switch is on is just named &#8220;on&#8221;.  To make things a bit more readable, they set this attribute to &#8220;getter=isOn&#8221;.  That way you can do something like this:</p>
<pre lang="objc">if(someSwitch.isOn)</pre>
<p>The getter= attribute is used purely for convenience or readability.</p>
<h3>setter=</h3>
<p>Similar to the getter=, it just gives a custom name to the setter.  The default setter is just the capitalized property name with set as a prefix (so the default setter for &#8220;petOwner&#8221; is &#8220;setPetOwner&#8221;.  This is again done purely for convenience or readability.  I personally see this less often, but it is perfectly valid.</p>
<h3>copy</h3>
<p>I have not used this one much, but here is what I have learned.  It is similar to strong, but instead of increasing the retain count and claiming ownership of an object, it copies the value of the object that it is assigned to, and takes strong ownership of that copy.  The object must conform to the NSCopying protocol to allow this to work.</p>
<h3>assign</h3>
<p>A pre-ARC attribute.  This is default behavior for primitive data types (like int, long, and float).  It was used similar to &#8220;weak&#8221; for pre-ARC programs.  It assumes the same ownership as &#8220;unsafe_unretained&#8221; mentioned below.  It appears okay to use in an ARC project, but should be limited to properties for primitive types.</p>
<h3>retain</h3>
<p>A pre-ARC attribute.  This is the older version of strong.  It claims ownership of the object and increases the retain count.  You will have to manually release the object to decrease its retain count (which will release it from memory when the retain count goes to 0).  You should not use this in an ARC project.</p>
<h3>unsafe_unretained</h3>
<p>A pre-ARC attribute.  This is similar to &#8220;weak&#8221;, but did not automatically set their value to nil if the referenced object was destroyed (as mentioned earlier).  You should not use this in an ARC project.</p>
<h2>Wrap-Up</h2>
<p>Those are all of the possible attributes you can use on properties.  Again, I started learning post-ARC, so my knowledge of assign, retain, and unsafe_unretained is somewhat lacking.  I will try to fill these out more as I learn more about them, but these are good starting points.  I know this is a rather long article, but I think this page will be useful if you ever need to know the difference between different property attributes.</p>
<p>I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps. Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do. Thanks!</p>
<h4>Sources</h4>
<p><a href="http://rypress.com/tutorials/objective-c/properties.html">http://rypress.com/tutorials/objective-c/properties.html</a></p>
<p><a href="http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html">http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html</a></p>
<p><a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html">http://clang.llvm.org/docs/AutomaticReferenceCounting.html</a></p>
<p>The post <a href="https://www.codingexplorer.com/property-attributes-in-objective-c/">Property Attributes in Objective-C</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Objective-C Categories</title>
		<link>https://www.codingexplorer.com/objective-c-categories/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 01 Mar 2014 03:39:28 +0000</pubDate>
				<category><![CDATA[Syntax]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=119</guid>

					<description><![CDATA[<p>Have you ever wished you could add a method to an existing class that you don&#8217;t have the code for? Well, now you can, with categories. Categories let you extend an existing class with whatever method you deem fit.  It is pretty useful to add helper methods to other classes that help parse the date [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/objective-c-categories/">Objective-C Categories</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Have you ever wished you could add a method to an existing class that you don&#8217;t have the code for?</p>
<p>Well, now you can, with categories.</p>
<p>Categories let you extend an existing class with whatever method you deem fit.  It is pretty useful to add helper methods to other classes that help parse the date in a way the class make perhaps did not intend.  You can also use it to split up your own classes so that if you have some big omni-class that does several things, you can opt in to just the parts you want by only including those categories.</p>
<p><span id="more-119"></span>To add a category, go to File -&gt; New File&#8230;, and select &#8220;Objective-C category&#8221; from the &#8220;Cocoa Touch&#8221; tab under iOS.  This will bring up an additional window, where you can name the Category in the &#8220;Category&#8221; textfield.  You then type or select the class you want to add it to, and it will output 2 very simple files.  For my example, I am adding a helper method to NSDate to tell me if something is in the past.  It is originally from <a title="iphone - How do I determine whether an NSDate (including time) has passed - Stack Overflow" href="http://stackoverflow.com/questions/8746016/how-do-i-determine-whether-an-nsdate-including-time-has-passed">this Stack Overflow question</a>, answered by Matt Galloway (<a title="Matt Galloway (mattjgalloway) on Twitter" href="https://twitter.com/mattjgalloway">@mattjgalloway</a> on twitter).  So if name the category &#8220;Helper&#8221;, I would have these files generated for me.</p>
<p>NSDate+Helper.h</p>
<pre lang="objc">@interface NSDate (Helper)

@end</pre>
<p>&nbsp;</p>
<p>NSDate+Helper.m</p>
<pre lang="objc">#import "NSDate+Helper.h"

@implementation NSDate (Helper)

@end</pre>
<p>Pretty simple.  Now to add my method to tell me if this date is in the past, I just make a method like normal, and add its prototype to the header file, so I end with.</p>
<p>NSDate+Helper.h</p>
<pre lang="objc">@interface NSDate (Helper)

-(BOOL)isInPast;

@end</pre>
<p>NSDate+Helper.m</p>
<pre lang="objc">@implementation NSDate (Helper)

-(BOOL)isInPast
{
    NSDate *testTime = self;
    if ([testTime timeIntervalSinceNow] &lt; 0.0)
    {
        return YES;
    }else
    {
        return NO;
    }
}

@end</pre>
<p>And that is all there is to it.  The code itself just asks what the time interval since now is, and if it is negative, that means it is in the past.   Now in any class that I want to use this, I have to import this category&#8217;s header file, and then I can ask an NSDate if it is in the past.</p>
<p>You import the category:</p>
<pre lang="objc">#import "NSDate+Helper.h"</pre>
<p>and somewhere in your program you could test it like this:</p>
<pre lang="objc">NSDate *someTime = [NSDate date];

if ([someTime isInPast]) {
    NSLog(@"It's in the past!");
} else
{
    NSLog(@"It is yet to come!");
}</pre>
<p>And this code snippet simply grabs the current time, puts it in to the object &#8220;someTime.&#8221;  Then it asks &#8220;someTime&#8221; right afterwards if it is in the past, and NSLogs an appropriate response.</p>
<p>Categories are a very powerful tool, so be careful how you use them.   Also, don&#8217;t use them to override a method, you should subclass the parent class if you want to do that.</p>
<p>I hope you found this article helpful.  If you did, don’t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps. Of course, if you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do. Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/objective-c-categories/">Objective-C Categories</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Storing data with NSUserDefaults</title>
		<link>https://www.codingexplorer.com/storing-data-with-nsuserdefaults/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 09 Jan 2014 02:43:41 +0000</pubDate>
				<category><![CDATA[Syntax]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=114</guid>

					<description><![CDATA[<p>How can you store data between application launches? There are plenty of ways, but here I will show you the simplest, NSUserDefaults. NSUserDefaults is a simple property list (aka plist) where an app can store simple data.  While there is no limit to its size (besides the device&#8217;s own limits), you should not store a large [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/storing-data-with-nsuserdefaults/">Storing data with NSUserDefaults</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>How can you store data between application launches?</p>
<p>There are plenty of ways, but here I will show you the simplest, NSUserDefaults.</p>
<p>NSUserDefaults is a simple property list (aka plist) where an app can store simple data.  While there is no limit to its size (besides the device&#8217;s own limits), you should not store a large amount of data here.  The file is written and read atomically (as a whole), so the more data that is in there, the longer that will take.  Nonetheless, it is a great place to store settings, high scores, and the like.</p>
<h1><span id="more-114"></span>Intro to Property Lists</h1>
<p>Property lists can only accept certain types of variables, so NSUserDefaults has that limitation.  You can store these types of variables:</p>
<ul>
<li>NSArray</li>
<li>NSData</li>
<li>NSDictionary</li>
<li>NSNumber</li>
<li>NSString</li>
</ul>
<p>Furthermore, the NSArray or NSDictionary must only contain the types listed above (yes, nesting of NSArray or NSDictionary is allowed).  Other items that conform to the NSCoding protocol can be archived as NSData, so you can store them in property lists if necessary.  I have not really looked in to NSCoding yet, so that will be the subject of some future post.  Also, the keys for the root of the property list, as well as any NSDictionary stored inside, must be NSStrings.</p>
<h1>Saving to NSUserDefaults</h1>
<p>Basically, all you have to do is load NSUserDefaults, and then tell it to save a value to a specific key.  Here is a simple example of writing an integer to NSUserDefaults:</p>
<pre lang="objc">NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:9001 forKey:@"HighScore"];
[defaults synchronize];</pre>
<p>As mentioned earlier, we loaded the NSUserDefaults plist to the object &#8220;defaults&#8221;.  We then told that object to set an integer for the key &#8220;HighScore&#8221;.  That final command to defaults to &#8220;synchronize&#8221; is basically to force a save.  It isn&#8217;t absolutely necessary, because this is called automatically every so often, but if you want to be sure to save the changes to NSUserDefaults right now, this is how.</p>
<p>Pretty simple, eh?</p>
<h1>Reading from NSUserDefaults</h1>
<p>Reading is even easier, as shown below:</p>
<pre lang="objc">NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger theHighScore = [defaults integerForKey:@"HighScore"];</pre>
<p>That&#8217;s all there is to it.  You just load NSUserDefaults, then tell it to retrieve a type for a specific key.  No need to synchronize or anything here, so 1 less line of code than saving.</p>
<p>One extra little tidbit here, you will notice that NSInteger has no asterisk after the type like NSUserDefaults does.  That is because NSInteger is actually just a typecast of long or int, depending on whether the system it is running on is 64-bit or 32-bit respectively, and not a normal Objective-C object.</p>
<h1>Conclusion</h1>
<p>You can read more on how to store different values in the <a title="NSUserDefaults Class Reference" href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsuserdefaults_Class/Reference/Reference.html" target="_blank">documentation</a> from Apple, but this is enough to get you started.  If you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do. Thanks!</p>
<p>&nbsp;</p>
<p>The post <a href="https://www.codingexplorer.com/storing-data-with-nsuserdefaults/">Storing data with NSUserDefaults</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Updating an app when returning from background in iOS</title>
		<link>https://www.codingexplorer.com/updating-an-app-when-returning-from-background-in-ios/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Tue, 07 Jan 2014 01:58:28 +0000</pubDate>
				<category><![CDATA[Syntax]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=110</guid>

					<description><![CDATA[<p>I am working on an app that needs to update the UI based on the current date when it is loaded.  I told it to do the update in my viewWillAppear, but about half the time it would not update when I loaded the program.  Shouldn&#8217;t viewWillAppear always be called when your view is about [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/updating-an-app-when-returning-from-background-in-ios/">Updating an app when returning from background in iOS</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I am working on an app that needs to update the UI based on the current date when it is loaded.  I told it to do the update in my viewWillAppear, but about half the time it would not update when I loaded the program.  Shouldn&#8217;t viewWillAppear always be called when your view is about to appear?  Apparently not, but I&#8217;ll tell you how I got the functionality I was looking for.</p>
<h1>Updating from the background with Notifications</h1>
<p>So, viewWillAppear will run every time your view is loaded from disk, or being called to be onscreen by a segue from another view.  However, when I leave the app, use some other apps and come back, as far as my app was concerned, this view never left.  It left as far as the system was concerned, but in my app&#8217;s little world, it just had the same view up as it did when I left the app.  When I left the app, I sent it to the background.  That is the difference.</p>
<p>So, how do I update my screen when it returns from the background?  There are two notifications that would be of help here.  They are:</p>
<ul>
<li>UIApplicationWillEnterForegroundNotification</li>
<li>UIApplicationDidBecomeActiveNotification</li>
</ul>
<p>As your program is brought back from the background, these two notifications are raised, in that order.  UIApplicationWillEnterForegroundNotification will run right before the view should appear onscreen, and UIApplicationDidBecomeActiveNotification should run just after.  In my previous post about <a title="Supporting Dynamic Type for iOS7 Apps" href="http://www.codingexplorer.com/supporting-dynamic-type-for-ios7-apps/">Supporting Dynamic Type</a>, I mentioned how to subscribe to notifications, but for simplicity&#8217;s sake, I will show you here.</p>
<p><span id="more-110"></span>I added this to my viewWillAppear:</p>
<pre lang="objc">[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(updateGUI)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:[UIApplication sharedApplication]];</pre>
<p>Then, in a new method updateGUI, just do whatever calculations or updates you need to do before the view comes back from the background.  In iOS7, the system takes a screenshot of your view when it is sent to the background, and shows that first when you load your app again, and then runs your code appropriately.  So even though we put this on the notification for before the view is visible, we still may see the previous value for a moment before the update is called.  I believe there are some ways to update the screenshot in the background every so often, but I do not know how yet.  I will look further in to it, but this still nonetheless fixed my original problem of only occasionally changing the value, and having to forcefully close the program and rerun it, or do some other action to call updateGUI.  I&#8217;m just taking this one step at a time.</p>
<h1>Cleaning up NSNotification Center afterwards</h1>
<p>And of course, we should clean up after ourselves, so again we will just unsubscribe from all notifications when we disappear.</p>
<pre lang="objc">-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}</pre>
<p>And that&#8217;s all there is to it.  I know this post is a bit shorter than usual, but I felt this was a useful tip to share.  I was confused about a problem I had, discovered how to fix it, and thought others might find the solution helpful.  If you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a>, and I&#8217;ll see what I can do.</p>
<p>Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/updating-an-app-when-returning-from-background-in-ios/">Updating an app when returning from background in iOS</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Supporting Dynamic Type for iOS7 Apps</title>
		<link>https://www.codingexplorer.com/supporting-dynamic-type-for-ios7-apps/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 04 Jan 2014 03:24:47 +0000</pubDate>
				<category><![CDATA[Syntax]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=103</guid>

					<description><![CDATA[<p>In a program I was working on, I decided to use Dynamic Type.  You can read about it here, but suffice it to say, it is a new way of handling text sizes in iOS7.  The user can set a value in their iOS device&#8217;s settings to set all text to be bigger or smaller [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/supporting-dynamic-type-for-ios7-apps/">Supporting Dynamic Type for iOS7 Apps</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In a program I was working on, I decided to use Dynamic Type.  You can read about it <a title="Text Programming Guide for iOS: Using Text Kit to Draw and Manage Text" href="https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html" target="_blank">here</a>, but suffice it to say, it is a new way of handling text sizes in iOS7.  The user can set a value in their iOS device&#8217;s settings to set all text to be bigger or smaller than default, for any app that implements Dynamic Type.  This is a bit more advanced than my other posts, but it is surprisingly easy to do, so I thought I would write a post about what I learned.</p>
<h1>Setup and using preferredFontForTextStyle</h1>
<p>First off, you have to create an outlet for any label, textfield, or whatever you have that you want to dynamically change the text size of, so as to have a place to set the font.  The easiest way to do this is to use the assistant editor on your view, and command+drag your text control to the assistant editor (in the @interface area of your .m for a private outlet).  Once you release it will ask you a few questions, and the defaults are fine usually, so you just have to give it a name.</p>
<p><span id="more-103"></span>I then made a single helper method that I would call to perform all of the appropriate updates.  It doesn&#8217;t take any arguments, it simply sets all of the fonts for the outlets you want to set.  This method is very simple.  All you do is set the font property of  the outlets we just made.  The key to using dynamic type, is the UIFont&#8217;s method preferredFontForTextStyle:.  This method takes an NSString that denotes the style that you want to set the text to.  There are 6 predefined styles that you can use in this method.  They are:</p>
<ul>
<li>UIFontTextStyleHeadline</li>
<li>UIFontTextStyleSubheadline</li>
<li>UIFontTextStyleBody</li>
<li>UIFontTextStyleFootnote</li>
<li>UIFontTextStyleCaption1</li>
<li>UIFontTextStyleCaption2;</li>
</ul>
<p>So with those, a sample method for this could look like:</p>
<pre lang="objc">-(void) doDynamicTypeThings
{
    self.someHeadline.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
    self.someBodyTextLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
}</pre>
<p>Now whenever this is called, you will update the font to whatever dynamic type says it should be.</p>
<h1>Using the Dynamic Type Helper Method</h1>
<p>I run this method in 2 places.  The first is an easy one.  It is just in viewWillAppear.  So when the view is about to appear, this is called and will set the font appropriately.  If you only did it here though, you leave a big hole in the program.  If you ran your program at one dynamic type setting, go out to settings, change the dynamic type slider, and went back to your program, it won&#8217;t update.  To fix this, we have to put doDynamicTypeThings somewhere else.</p>
<p>We need to listen for when these sort of updates happen, so that it will see that there was a change, and rerun our Dynamic Type method.  To do that, we have to subscribe to a notification that tells us such, and that one is UIContentSizeCategoryDidChangeNotification.  I added the my subscription to this notification to viewWillAppear as well, so my viewWillAppear looks like:</p>
<pre lang="objc">- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(preferredContentSizeChanged:)
                                                 name:UIContentSizeCategoryDidChangeNotification
                                               object:nil];
    [self doDynamicTypeThings];
}</pre>
<p>The astute will see that that message to NSNotificationCenter doesn&#8217;t actually run my doDynamicTypeThings.  That message is sent at the end of viewWillAppear, but that only happens when viewWillAppear runs.  We now need to implement the selector specified in our message to NSNotificationCenter.  In there we run the actual method we need, so it looks like:</p>
<pre lang="objc">- (void)preferredContentSizeChanged:(NSNotification *)notification
{
    [self doDynamicTypeThings];
    [self.view setNeedsLayout];
}</pre>
<p>So now when we get that notification, we will run this method, which runs our method to change all of the fonts.</p>
<h1>Cleaning up NSNotification Center when we are done</h1>
<p>I also added the command to unsubscribe to this in viewWillDisappear, so we don&#8217;t get notifications if this view is not up, so it looks like:</p>
<pre lang="objc">-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}</pre>
<p>In this case though, I actually told NSNotificationCenter to remove my view controller itself as an observer entirely, so this will remove ALL notifications I am subscribed to.  There is a way to specify a certain notification, but I felt it was unnecessary here.</p>
<h1>Conclusion</h1>
<p>While this post might make it look long, we basically did this:</p>
<ol>
<li>Created outlets for anything we wanted Dynamic Type to resize.</li>
<li>Set fonts of this outlets to the appropriate font using preferredFontForTextStyle: in a helper method.</li>
<li>Ran that helper method in viewWillAppear.</li>
<li>Subscribed to the UIContentSizeCategoryDidChangeNotification notification.</li>
<li>Ran the helper method when that notification is received.</li>
<li>Unsubscribed from all notifications in viewWillDisappear.</li>
</ol>
<p>That&#8217;s about all there is to it.  While people probably won&#8217;t change this value very often, it is a good idea to update in case they do.  So now if they need the text in your app a bit bigger to read, it will update appropriately, without making them have to force quit the app or move back and forth from another view in your app to force viewWillAppear to run again.</p>
<p>I hope this was helpful for implementing Dynamic Type in your apps.  If you have any questions, don&#8217;t hesitate to contact me on twitter <a title="Coding Explorer (CodingExplorer) on Twitter" href="https://twitter.com/CodingExplorer" target="_blank">@CodingExplorer</a> , and I&#8217;ll see what I can do.</p>
<p>Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/supporting-dynamic-type-for-ios7-apps/">Supporting Dynamic Type for iOS7 Apps</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Objective-C Custom Initializers</title>
		<link>https://www.codingexplorer.com/objective-c-custom-initializers/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 21 Nov 2013 03:46:02 +0000</pubDate>
				<category><![CDATA[Syntax]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=95</guid>

					<description><![CDATA[<p>Let&#8217;s say you are programming a flashcard app.  In the model for these flashcards, you will have a flashcard object, and each flashcard has 2 strings as properties (one for the front of the card, and one for the back).  You could just alloc-init the card, and then set them later&#8230; but what use is [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/objective-c-custom-initializers/">Objective-C Custom Initializers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Let&#8217;s say you are programming a flashcard app.  In the model for these flashcards, you will have a flashcard object, and each flashcard has 2 strings as properties (one for the front of the card, and one for the back).  You could just alloc-init the card, and then set them later&#8230; but what use is a blank flashcard?  Why not only initialize a flashcard when those piece of data are provided?  That is what custom initializers are for.</p>
<p>Here is an example of making this flashcard class with its own custom initializer.</p>
<p>In FlashCard.h:</p>
<pre lang="objc">@interface FlashCard : NSObject

@property (strong, nonatomic) NSString *frontText;
@property (strong, nonatomic) NSString *backText;

- (instancetype)initWithFront:(NSString *)onFront back:(NSString *)onBack;

@end</pre>
<p>In FlashCard.m:</p>
<pre lang="objc">#import "FlashCard.h" 

@implementation FlashCard

- (instancetype)initWithFront:(NSString *)onFront back:(NSString *)onBack
{
    if ((self = [super init])) {
        _frontText = onFront;
        _backText = onBack;
    }
    return self;
} 

@end</pre>
<p>And that is pretty much all there is to it.  While it is not a lot of text, there are a few things that I had to look up a bit to understand what was going on in these statements, so I will go into more depth to explain some of the new things shown here.</p>
<h1><span id="more-95"></span>Super init and instancetype</h1>
<p>What is instancetype?  We&#8217;ll get there, but to make it make the most sense, I need to skip ahead a moment.</p>
<p>On that if-statement line, you see how we assign the result of [super init] to self?  For that part, we are calling the initializer of the superclass that this class is inheriting from.  In the header file, you can see that the class inherits from NSObject (as most classes we make do, at least after several levels of inheritance).  That means you just assigned an NSObject* to the self variable.  Well, technically, you assigned an id to it, but it is an id that stands for an NSObject*.</p>
<p>I am still learning this, but from what I&#8217;ve found out so far, that is part of the reason for that wacky instancetype return type.  Previously in Objective-C, you would just set the return type to &#8220;id&#8221;, but now you can use instancetype instead.  It basically tells the compiler that it will return an object that is the same type this message (init) was sent to, in this case being the &#8220;Flashcard&#8221;.  I am still not entirely sure why you cannot tell it that it will return a (Flashcard *), but I think it is related to the fact that we just instantiated it as an NSObject*.  When I learn more to better explain it, I will update this post, but for now, here is a post from NSHipster about <a title="instancetype" href="http://nshipster.com/instancetype/" target="_blank">instancetype</a>.</p>
<p>So anyway, back to that if statement.  That kind of crazy &#8220;conditional&#8221; there as I said before, is setting the result of [super init] to the self variable.  If the initialization fails for some reason, that message will return nil.  If it returns nil, then you will exit that if statement, and just return what is in self, which is nil (to say that this initialization also failed).  If it does successfully initialize, it will put that NSObject* (or id of one) into self, and continue in to the if statement.</p>
<h1>Writing to instance variables directly?!</h1>
<p>Now, inside there I am doing something that you in general should not do, but from what I&#8217;ve found, is recommended in the initializer.  As we saw in the .h file, I have made 2 public properties for frontText and backText.  When I make a property, as I&#8217;ve mentioned before in my post <a title="Objective-C Classes and Usage of Variables" href="http://www.codingexplorer.com/objective-c-classes-and-usage-of-variables/" target="_blank">Objective-C Classes and Usage of Variables</a>, Objective-C automatically makes setters, getters, and an instance variable (aka &#8220;field&#8221;) to store them.  The default instance variable it makes is the name of the property preceded by an underscore (so _frontText and _backText).</p>
<p>In most other places in code, you should only use the properties, such as self.frontText and self.backText, and you technically can here, but you may not want to.  The main reason I have found is that in more advanced programs, the setter may depend on a fully formed object to fulfill its duty.  In this program, it probably wouldn&#8217;t matter, but if I had another string, that would store both the front and back in the same string for some reason (like to list off the total contents of the flashcard), and that string was updated when you used the setter.  It would read the string you just set, and it would try to read the string that you haven&#8217;t written yet.  You would be better off just writing to the instance variables directly, and then calling that update method.  It is a contrived example, but that would be one reason you might not want to.</p>
<p>Anyway, after you set initialize self itself, and then fill in those instance variables, all you have to do now is return self to the class that called this, and you have yourself a fully formed Flash Card.  If there are default values, you could override init, and fill them in.  If there aren&#8217;t default values, you could just return nil from that overridden init.</p>
<p>I hope you found this article helpful.  If you did, don&#8217;t hesitate to share this post on twitter or your social media of choice.  The blog is still pretty new, and every share helps.</p>
<p>Thanks!</p>
<p>The post <a href="https://www.codingexplorer.com/objective-c-custom-initializers/">Objective-C Custom Initializers</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Top Objective-C Learning Resources</title>
		<link>https://www.codingexplorer.com/top-objective-c-learning-resources/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Sat, 16 Nov 2013 00:47:44 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=88</guid>

					<description><![CDATA[<p>When I decided to start learning Objective-C, I started looking for a lot resources to assimilate, to learn as much as I could.  I have been a big fan of podcasts for the last couple years, so I searched for podcasts about iOS and Objective-C programming.  Early on, I found this post on the Accidental [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/top-objective-c-learning-resources/">Top Objective-C Learning Resources</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>When I decided to start learning Objective-C, I started looking for a lot resources to assimilate, to learn as much as I could.  I have been a big fan of podcasts for the last couple years, so I searched for podcasts about iOS and Objective-C programming.  Early on, I found this post on the <a title="Accidental Technologist" href="http://accidentaltechnologist.com/objective-c-2/7-great-ios-and-mac-developer-podcasts-to-learn-from-today/" target="_blank">Accidental Technologist</a> that listed several good podcasts in this field.  I will cover them here myself as well, but I thought I should call out where I found these in the first place.</p>
<p>Firstly, of course, are the Apple WWDC videos and sample code provided there if you are a registered developer at the <a title="iOS Dev Center" href="https://developer.apple.com/devcenter/ios/index.action" target="_blank">iOS Dev Center</a>.</p>
<h1>Video</h1>
<p><a title="Developing iOS 7 Apps for iPhone and iPad" href="https://itunes.apple.com/us/course/developing-ios-7-apps-for/id733644550" target="_blank">Stanford&#8217;s Developing for iOS Classes on iTunes U</a> &#8211; These are absolutely amazing.  Out of all of the resources I have gone through, these have been the most helpful in getting me going.  Profesor Paul Hegarty covers many different aspects of Objective-C and iOS, from the basics to Core Data, and does so in a very casual and easy to understand way.</p>
<p>When gathering links for this blog post, I found that this iOS 7 version of the class is currently in progress, so I have linked it here.  I will be going back through these to see what new tidbits I can find that are iOS 7 specific.</p>
<h1><span id="more-88"></span>Podcasts</h1>
<h2>Objective-C Podcasts</h2>
<p><a title="Developing Perspective" href="http://developingperspective.com" target="_blank">Developing Perspective</a> by David Smith &#8211; As David Smith says in his intro, &#8220;Developing Perspective is a podcast discussing news of note in iOS Development, Apple, and the like.&#8221;  He is an independent iOS developer and definitely helps impart the what it is like to be one, which I am currently aspiring to be.</p>
<p><a title="Edge Cases" href="http://edgecasesshow.com" target="_blank">Edge Cases</a> by Andrew Pontious and Wolf Rentzsch &#8211; This is one of the most technical of the Objective-C podcasts I listen to.  A lot of it still goes over my head, but hearing the history of many things that make of modern aspects of iOS and Mac development is very interesting, and they DEFINITELY do their homework.</p>
<p><a title="iDeveloper | Stuff for OS X and iOS Developers" href="http://ideveloper.co" target="_blank">The iDeveloper Podcast</a> by Steve Scott and John Fox &#8211; This is a classic that is still going strong.  Scotty and John Fox  know their stuff and interview many others in the Objective-C developer space.</p>
<p><a title="NSBrief" href="http://nsbrief.com" target="_blank">NSBrief</a> by Saul Mora &#8211; Another classic in this space.  Like the iDeveloper Podcast, he also interviews many others in the Objective-C developer space.  Recently NSBrief and the iDeveloper Podcast have joined forces, so they will probably working together more in the future.</p>
<h2>Apple Ecosystem Podcasts</h2>
<p><a title="Accidental Tech Podcast" href="http://atp.fm" target="_blank">Accidental Tech Podcast</a> by Casey Liss, Marco Arment, and John Siracusa &#8211; This is more about Apple as whole, but they are 3 professional Objective-C developers that have a lot of insight in this field.  I also find this one of the most entertaining of the podcasts I listen to on this subject.</p>
<p><a title="Bitsplitting.org | Chasing the impossible with Daniel Jalkut" href="http://bitsplitting.org" target="_blank">Bitsplitting</a> by Daniel Jalkut &#8211; This is currently on hiatus, but Daniel interviews other people in the Apple Ecosystem.</p>
<p><a title="Core Intuition" href="http://www.coreint.org" target="_blank">Core Intution</a> by Daniel Jalkut and Manton Reece &#8211; Another particularly entertaining podcast.  They talk discuss current apple news and what it is like as Mac and iOS developers.</p>
<p>&nbsp;</p>
<p>This is by no means an exhaustive list, but I feel I have gotten a lot from these in particular.</p>
<p>The post <a href="https://www.codingexplorer.com/top-objective-c-learning-resources/">Top Objective-C Learning Resources</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>NSString &#8211; Objective-C Class Reference</title>
		<link>https://www.codingexplorer.com/nsstring-objective-c-class-reference/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 14 Nov 2013 07:19:21 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=85</guid>

					<description><![CDATA[<p>I have mentioned NSString in previous posts, so I might as well write about it in my new set of class reference posts.  I also keep forgetting the formatting specifiers, and so I&#8217;ll put up a table of those for everyone to see when you want to know the correct specifier for a formatted string. [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/nsstring-objective-c-class-reference/">NSString &#8211; Objective-C Class Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I have mentioned NSString in previous posts, so I might as well write about it in my new set of class reference posts.  I also keep forgetting the formatting specifiers, and so I&#8217;ll put up a table of those for everyone to see when you want to know the correct specifier for a formatted string.  As we&#8217;ve seen before, an NSString is an object that represents a block of text.  The name presumably comes from the fact that it is a string of characters, though that is just supposition, but does make it slightly easier to remember.  For a little history, in C, a string was an array of an 8-bit variable named &#8220;char&#8221;, which was short for character.  In each of those spots of an array was a number that would denote a letter based off of the ASCII standard.  If you&#8217;re curious, here is a link to a copy of the <a title="ASCII Table" href="http://www.asciitable.com/">ASCII Table</a>.  At the end of the string, to denote the end, was a NUL character, which is denoted by the number 0.  Unlike most of my trips into history though, this is actually still quite relevant to Objective-C.</p>
<h1><span id="more-85"></span>Creating Strings</h1>
<p>The simplest was to create an NSString is be creating a string literal, like so:</p>
<pre lang="objc">NSString *myFancyString = @"Hello World!  I am a string!"</pre>
<p>Why is it called a string literal?  Because it is the string literally written in the code.  I know, it&#8217;s a bit simplistic, but it is a term that is used for them.  Most useful string are generated programaticcaly, as I will show next, so it does have some significance.</p>
<p>So for this string, one important thing to note is that @ sign before the quotes.  Without it, you would actually be creating a standard C, null-terminated string.  X-Code then complains &#8220;Implicit conversion of a non-Objective-C pointer type &#8216;char *&#8217; to &#8216;NSString *&#8217; is disallowed with ARC.&#8221;  When you add that @ sign, it commands the compiler to create it as an NSString.  The @ sign is used in a few places in for shorthand like this, such as in NSSArray, where it can help with making arrays.  Other that, nothing is too special about this line, an NSString literal must start with a @ sign, and and be enclosed in double quotes.  Single quotes normally denotes a single character in C and apparently gives warnings instead of syntax errors, but definitely do not do what you would want with the string.  Single quote can be used for single characters, but that&#8217;s another story.</p>
<p>To generate a string programatically using variable values, you would do something similar to the code below:</p>
<pre lang="objc">NSString *somethingMissing = @"cupcakes";
int amountLeft = 5;
NSString *someSentence = [NSString stringWithFormat:@"We seem to have only %d of our %@ left!", amountLeft, somethingMissing];</pre>
<p>So, basically, you send the NSString class a message requesting that it use the string you send it, and replace some placeholders in it with data stored in variables.  The &#8220;%d&#8221; and &#8220;%@&#8221; are placeholders for certain types of variables.  After the main string you see some variables separated by commas.  These fill in those placeholders in the same order that the placeholders are written, so amountLeft left&#8217;s value will replace the %d, and somethingMissing will replace the %@.  Which identifier goes with what?  That is what I mentioned at the beginning that I would put a table in for.  For the full table, see that <a title="String Programming Guide: String Format Specifiers" href="https://developer.apple.com/library/ios/documentation/cocoa/conceptual/Strings/Articles/formatSpecifiers.html">String Programming Guide: String Format Specifiers</a>, but here are some excerpts that I will probably use the most often.</p>
<table border="1&quot;">
<tbody>
<tr>
<th>Identifier</th>
<th style="text-align: left;">What it replaces it</th>
</tr>
<tr>
<td>%@</td>
<td>An Objective-C Object.  It calls the method &#8220;description&#8221; which outputs a string representation of whatever value it is.</td>
</tr>
<tr>
<td>%d or %D</td>
<td>A Signed 32-bit integer (int)</td>
</tr>
<tr>
<td>%u or %U</td>
<td>An unsigned 32-bit integer (unsigned int)</td>
</tr>
<tr>
<td>%f</td>
<td>A 64-bit floating-point number (double), be default to 6 decimal places, so 5.341847924 comes out as 5.341848.</td>
</tr>
</tbody>
</table>
<h1>Are these NSStrings equal?</h1>
<p>How can you find the answer to that question in Objective-C?  It would be nice if you could say  if( someString == anotherString), but that would only try to equate their pointers.  In this case you have to ask NSString to do it for you, with:</p>
<pre lang="objc">NSString *someCat = @"Orange Tabby";

if ([someCat isEqualToString:@"Orange Tabby"])
{
    NSLog(@"It's an Orange Tabby!");
}

if ([someCat isEqualToString:@"Corgi"])
{
    NSLog(@"It's a Corgi!");
}</pre>
<p>Here we are asking the someCat instance of NSString if it is equal to another string.  This message responds with a boolean &#8216;YES&#8217; or &#8216;NO&#8217;, which will inform the if statement what to do.  In this case it will print out &#8220;It&#8217;s an Orange Tabby!&#8221;, but will not print &#8220;It&#8217;s a Corgi!&#8221;.</p>
<p>&nbsp;</p>
<p>That&#8217;s it for now.  I should be updating this more in the future with some other useful abilities of the NSString class.  I hope this has been a help to you, and good luck in learning Objective-C.</p>
<p>The post <a href="https://www.codingexplorer.com/nsstring-objective-c-class-reference/">NSString &#8211; Objective-C Class Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>NSDictionary &#8211; Objective-C Class Reference</title>
		<link>https://www.codingexplorer.com/nsdictionary-objective-c-class-reference/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Mon, 04 Nov 2013 22:04:31 +0000</pubDate>
				<category><![CDATA[Class Reference]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=83</guid>

					<description><![CDATA[<p>Have you had a collection of objects that you want to by name?  Lets say you had an object that contains contact info for a person.  If I wanted to see the contact information for somebody, I&#8217;d want to just tell something, &#8220;Hey, give me Jimmy&#8217;s contact info&#8221;, and it would get it for me. [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/nsdictionary-objective-c-class-reference/">NSDictionary &#8211; Objective-C Class Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Have you had a collection of objects that you want to by name?  Lets say you had an object that contains contact info for a person.  If I wanted to see the contact information for somebody, I&#8217;d want to just tell something, &#8220;Hey, give me Jimmy&#8217;s contact info&#8221;, and it would get it for me.  That is exactly what NSDictionary does for you.</p>
<p>NSDictionary is way to perform easy lookups for objects stored in the dictionary, via a key of some sort.  It basically stores data in something called a &#8220;key value pair&#8221;.  I will use the even simpler example of looking up the definition of a word in a standard Miriam-Webster style dictionary.  The word you are looking up is the &#8220;key.&#8221;  The definition you are trying to find for that word is the &#8220;value.&#8221;  In this post, I&#8217;ll go over some of the basics.</p>
<h1><span id="more-83"></span>Creating a NSDictionary</h1>
<p>There are many ways to create it, but I will go over some of the simpler ones here.  The first one I learned is making a NSDictionary from another NSDictionary.  You might be saying to yourself, &#8220;How is that useful when you&#8217;re learning?  Making a NSDictionary from another one means I need one in the first place!&#8221;  And you would be right, so that is what Apple gives you!</p>
<pre lang="objc">NSDictionary *wordDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"A friendly mammal commonly kept as a pet", @"Cat",
@"An awesome smartphone", @"iPhone",
@"An informative and helpful blog about Objective-C", @"CodingExplorer.com", nil];</pre>
<p>Shameless self plug aside, that is a very easy way to make an initial dictionary.  You just tell the NSDictionary class to make one based off of the keys you give it.  There are a few VERY important things to know about how to use this though.</p>
<p>The order is Value, then Key &#8212; While my example makes it obvious, you must put the Value object first, then its associated key.  One reference I found had this backwards, which had me quite frustrated when it didn&#8217;t work.  I figured it out eventually be giving my dictionary the command [wordDictionary allKeys], which returns an NSArray of all keys, and found it was telling me the equivalent of the definitions in this example, instead of the words.</p>
<p>It must be terminated with nil &#8212; As far as my research has shown me, that nil at the end just says that the list of objects is complete.</p>
<p>A similar method is:</p>
<pre lang="objc">dictionaryWithObjects:(NSArray *)values forKeys:(NSArray *)keys</pre>
<p>This one does the same thing, but in this case you have two NSArrays.  One filled with all values, the other with all keys, then it makes a dictionary by stepping through those.</p>
<p><strong>Update 11/11/13:</strong>  I have recently learned from the Stanford iOS classes of a newer way to create an NSDictionary that is much simpler.  It&#8217;s syntax is as follows:</p>
<p>NSDictionary *someDictionary = @{key1 : value1, key2 :value2, &#8230;};</p>
<p>So this one has the order I like where it is key then value, and it is a LOT less verbose.  Also, this one does not need to be nil terminated.  If you wanted just 2 things, you would just put the  end curly brace where that last comma is.  If you wanted more ,just repeat the pattern.  Similar to how when Apple made it easy to make an NSString from a C string with the @ sign, they use it here to provide a shortcut.</p>
<h1>Reading from a Dictionary</h1>
<p>Now that we have something stored, how do we get it out?  While there are plenty of ways, this is the way I am currently using:</p>
<pre lang="objc">NSString *definitionOfiPhone = [wordDictionary objectForKey:@"iPhone"];</pre>
<p>This way is pretty self explanatory, that it sends a message to the wordDictionary requesting an object associated with the key, which in this case is an NSString of &#8220;iPhone.&#8221;</p>
<p>Something important to note, the objects and keys can be just about anything that inherits from NSObject, which is almost anything you&#8217;ll deal with except for C primitives like int, double, etc.  For the sake of simplicity and explanation, I used an NSString for both, but you could have them as NSNumbers, or your own custom class.  The only thing they can&#8217;t be is &#8220;nil&#8221;, but you could use NSNull as a placeholder.</p>
<p><strong>Update 11/11/13:</strong>  As with my above note about an easier way to make an NSDictionary, I also learned about a much easier way to ready from one.  This way is much similar to how I read them in a dictionary in C#, so it feels a lot more familiar, and again, is a lot less verbose.</p>
<pre lang="objc">NSString *definitionOfiPhone = wordDictionary[@"iPhone"];</pre>
<p>You just basically use they key as if it were an index in an array.</p>
<h1>Things to come?</h1>
<p>I had a bit of trouble finding everything I wanted in one place for this, so I thought it would be helpful for others that want a 1 stop shop to learn about things.  When I was learning about C#, the website <a title="www.dotnetperls.com" href="http://www.dotnetperls.com/" target="_blank">dotnetperls</a> was invaluable to me.  I am thinking I will make some pages like this one for other classes I learn about to help in Objective-C like Dot Net Perls helped me in C#.  If you do need to learn C# for something as well, definitely check out <a title="www.dotnetperls.com" href="http://www.dotnetperls.com/" target="_blank">dotnetperls</a>.  But anyway, I hope this was helpful, I am thinking I may update these posts as I learn more, to make them references for what I learn about specific classes like this.  In other words, this is probably only the begining for this reference page, and hopefuly is the harbinger of other class references.</p>
<p>The post <a href="https://www.codingexplorer.com/nsdictionary-objective-c-class-reference/">NSDictionary &#8211; Objective-C Class Reference</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Objective-C Classes and Usage of Variables</title>
		<link>https://www.codingexplorer.com/objective-c-classes-and-usage-of-variables/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 13 Sep 2013 04:04:11 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=73</guid>

					<description><![CDATA[<p>So, for a little behind the scenes action.  The previous post about Header Files was originally going to be about classes.  But then after I started writing, I realized if I continued on to talking about classes, the post was going to be longer than I would want to read, so I decided to just [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/objective-c-classes-and-usage-of-variables/">Objective-C Classes and Usage of Variables</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So, for a little behind the scenes action.  The previous post about <a title="Header Files" href="http://www.codingexplorer.com/header-files-a-history-lesson/" target="_blank">Header Files</a> was originally going to be about classes.  But then after I started writing, I realized if I continued on to talking about classes, the post was going to be longer than I would want to read, so I decided to just split off the header file topic entirely, and save more discussion of classes for later.  That&#8217;s why I wrote about such an esoteric topic as &#8220;Header Files&#8221;.  I also like the word esoteric, so expect that to show up in this blog every so often.</p>
<p>Anyway, back to what I originally was going to write about, classes.  Classes are probably the most important thing in object oriented programming.  They are the very constructs that objects are created from.  For a physical analogy, lets say that we want to make a &#8220;landVehicle&#8221; class, by which I mean somethign that could discuss land vehicles like cars, trucks, tanks, whatever.</p>
<p>Aspects of Land Vehicles</p>
<ul>
<li>They have variable speeds to drive at</li>
<li>They have an external color</li>
<li>They can drive different directions</li>
</ul>
<p>So, if we had a game that needed land vehicles in it, we may want to write a class that describes them, so that the game can display them or use them somehow.  The first two describe an specific attribute of the land vehicle, while the third one refers to something it can do.  In a class, those first two could be stored as variables, and the third one could be used as a method, to cause the vehicle to drive a certain direction.  We&#8217;ve covered methods before, so I am going to discuss some of the details about variables below.</p>
<p><span id="more-73"></span>In Objective-C, variables, in the end, are stored as something called a field.  A field is the simplest way to store a variable, you basically just say what type of variable it is, and its name.  There is also a slightly more advanced version of storing variables, that is a wrapper over a field, to give you a bit more control, this one is called a property.  If you know a bit about Java, a property is basically the getters and setters that one would write to use a field.  In general, one should use properties when storing a variable in Objective-C.  It allows you to add code between the actual setting or getting of an object, instead of giving direct access of it to whatever calls the for the variable.  This could be used for many things, like refusing to take a speed value greater than 100 for your land vehicle, assuming 100 was its top speed.  Here is an example of a property, with its backing field used in a simple program.</p>
<pre lang="objc">@interface landVehicle()
@property (strong, nonatomic) NSString *color;
@end

@implementation landVehicle
@synthesize color = _color;   //This tells it to generate the setters and getters, and tells them to point to a field named _color

-(NSString *)color
{
    return _color;
}

-(void)setColor:(NSString *)color
{
    _color = color;
}
@end</pre>
<p>As stated in the comments, the @synthesize generates the setter and getter, but it does so invisibly to the code writer.  You don&#8217;t normally see these, but this is what it generates under the hood.  However, if you wanted to override the defaults (which are basically what you see here), you would write the one you wanted to override like this, and add your code as appropriate.</p>
<p>The actual creation of the property (the @property line) has a few unfamiliar things in it.  Firstly, this is an object, and so what this actually is, is a pointer to a place in memory where the object is, which is signified by that asterisk.</p>
<p>The &#8220;strong&#8221; refers to how it will be memory managed.  Basically, if an field has no strong pointers to it, it is deleted from memory.  From my experience so far, most properties should be set to &#8220;strong&#8221;.  One reason to use a &#8220;weak&#8221; pointer, is to avoid something called a &#8220;retain cycle&#8221;, which would be a time when two strong pointers refer to each other, like a parent object having a strong pointer to a child object, and the child object having a strong pointer to a parent object.  Again, I&#8217;m still new, so I haven&#8217;t run in to this yet, but that is what I&#8217;ve read so far about it.</p>
<p>The &#8220;nonatomic&#8221; is something to say that the property is not thread-safe.  I have even less experience with this one, but basically if you have a multithreaded program, and 2 or more threads wanted to read or write to the same property at the same time, the program needs to treat the properties in a special way, to keep things consistent and less crash inducing.  For instance, if you had a string that stored the value &#8220;Pumpernickel&#8221;, and one thread wanted to change it to &#8220;Baguette&#8221;, and another thread wanted to read that variable at almost the same time, without locking, the one reading it might get &#8220;Baguernickel&#8221;, since it was in the process of writing it.  I have not tested this (I don&#8217;t really know multithreaded programming in Objective-C, yet), and this may not be how a string is actually modified, but this is more to explain why you might lock it to have it wait until the write operation is complete.  Atomic should make sure you either get &#8220;Pumpernickel&#8221; or &#8220;Baguette&#8221;, depending on if the call to the getter happens during the write, or shortly thereafter.  If you want to read more about the difference this <a href="http://stackoverflow.com/a/589392/1093030" target="_blank">StackOverflow answer</a> explains it quite nicely.  Anyway, in general, until you start dealing with multiple threads, just use &#8220;nonatomic.&#8221;</p>
<p>A REALLY common reason to override the getter, is something that is called &#8220;lazy loading.&#8221;  Below is an example of such, with an explanation after.</p>
<pre lang="objc">-(NSString *)color
{
    if(!_color)
    {
        //_color = [[NSString alloc] init];   //General initialization
        _color = @"Silver";    //Initialization with an NSString default
    }
    return _color;
}</pre>
<p>What this basically adds, is that if _color is not initialized (or more specifically, if it IS equal to nil), then set to the default color of &#8220;Silver&#8221; as a string.  In this case, there is a short cut for initialization of a string, but the commented out line would be a more general form which would just create an empty NSString.  This lets you load the actual field with an object only after it is needed, which keeps you from having to spread if(color != nil) everywhere, you can just put it right here and it will always respond with a valid object.</p>
<p>So, that is a bit more about classes and the usage of variables in Objective-C.  Thanks for reading this post and stay tuned for more field notes from the Coding Explorer.</p>
<p>The post <a href="https://www.codingexplorer.com/objective-c-classes-and-usage-of-variables/">Objective-C Classes and Usage of Variables</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Header Files, A History Lesson</title>
		<link>https://www.codingexplorer.com/header-files-a-history-lesson/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 23 Aug 2013 01:21:22 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=63</guid>

					<description><![CDATA[<p>Classes are a very important part of object oriented programming.  A class is the blueprint for any object in an object-oriented programming language.  It encapsulates variables and methods related to an object, and a program creates instances of objects to work with.  We can discuss specifics about classes in a later post, but for now, [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/header-files-a-history-lesson/">Header Files, A History Lesson</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Classes are a very important part of object oriented programming.  A class is the blueprint for any object in an object-oriented programming language.  It encapsulates variables and methods related to an object, and a program creates instances of objects to work with.  We can discuss specifics about classes in a later post, but for now, I wanted to talk a little about header files.  Classes in Objective-C are comprised of 2 files, the implementation file, and a header file.  What is a header file you may ask?  Keep reading and you will learn, and even if you do know, there might be some useful history you may not know.</p>
<h1><span id="more-63"></span>Objective-C Classes:  A Tale of Two Files</h1>
<p>This goes all the way back to C.  Back in C, if you wanted to call a method form somewhere, its signature had to be written somewhere higher in the text of the file.  By somewhere higher, I literally mean an earlier line number, like if you wanted to call a method from line 20 of the file, something that denoted its signature had to be in lines 1-19.  There were a few ways to do this.</p>
<p>You basically had 3 ways to deal with this, and 2 of them are essentially the same.</p>
<ol>
<li>You could just simply write the whole method above where it is called.  This could have some annoying consequences of just always having to make sure you had these in some sort of usage order, and it would not make it easy to separate things into functional areas in the same code file.</li>
<li>You could write something called a &#8220;prototype&#8221; near the top of the file.</li>
<li>You could write the prototype in a header file, and #include it in your main code file.</li>
</ol>
<p>A prototype is basically the first line of a method, written almost like a function call, for example:</p>
<pre lang="c">void anAwesomeMethod(int aNumber, int anotherNumber);</pre>
<p>In my research for this article, I learned that, at least in C, that is just a Pre-compiler command to replace that whole #include line with the entire contents of the .h file, which basically does what we said before of putting the prototypes at the top.  So, to the computer, options 2 and 3 are basically the same, they just appear different for us.</p>
<h1>Modern Objective-C</h1>
<p>In Objective-C, you do not need to care about the order your declare methods, for the most part, so you do not generally need that advantage header files give.  There are some reasons to forward declare methods, but they are much less common, and can be discussed later.  In Objective-C, header files are more often used as an external interface.  If another class will call your class, it should only call items mentioned in your header file.  You also should in general only have #includes in your header file for things that are necessary for the header file to make sense, and any privately used ones, can be written in your implementation file.  In Objective-C, your implementation file is a &#8220;.m&#8221; file, and your header file is still the familiar &#8220;.h&#8221; file.</p>
<p>Thanks for reading this post, and stay tuned for more from the front line of somebody learning Objective-C.</p>
<p>The post <a href="https://www.codingexplorer.com/header-files-a-history-lesson/">Header Files, A History Lesson</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Objective-C Syntax Primer 1:  Methods</title>
		<link>https://www.codingexplorer.com/objective-c-syntax-primer-1-methods/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Thu, 01 Aug 2013 01:32:32 +0000</pubDate>
				<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Syntax]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=52</guid>

					<description><![CDATA[<p>Getting used to Objective-C Syntax My previous experience with programming is mostly with languages similar to C in syntax.  So when I started to learn Objective-C, while it is still a subset of C, it diverged in a much different fashion to its brethren.  To give a little history lesson, Objective-C was began in the [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/objective-c-syntax-primer-1-methods/">Objective-C Syntax Primer 1:  Methods</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Getting used to Objective-C Syntax</h1>
<p>My previous experience with programming is mostly with languages similar to C in syntax.  So when I started to learn Objective-C, while it is still a subset of C, it diverged in a much different fashion to its brethren.  To give a little history lesson, Objective-C was began in the 1980s, as basically a combination of the languages &#8220;<a title="C" href="http://en.wikipedia.org/wiki/C_(programming_language)" target="_blank">C</a>&#8221; and &#8220;<a title="Smalltalk" href="http://en.wikipedia.org/wiki/Smalltalk" target="_blank">Smalltalk</a>&#8220;.  Other C-derived languages include C++ (obviously) and Java.  Other Smalltalk-derived languages include Python and Ruby.  Since I am not particularly versed in Python or Ruby though, the aspects borrowed from that side of Objective-C&#8217;s family tree are currently a bit of a mystery to me, hence my trying to pass on what I&#8217;ve learned about the syntax.</p>
<h1><span id="more-52"></span>Using methods in C</h1>
<p>So, in C based languages you usually create a method like this:</p>
<pre lang="c">int someMathFunction(int length, int width);</pre>
<p>And call it like this:</p>
<pre lang="c">someMathFunction(5,10);</pre>
<p>Simple enough, though one issue when you&#8217;re calling it, you can&#8217;t see what the parameters are at a glance.  If you want to see them, you have to look up the prototype of the method to know what each of the parameters are.  Unless you named the variables really well in the code where you called the function, this can be rather hard to understand at a glance.  Some IDEs assist with this by showing the prototype when you hover over a method call, or see it in code completion, but it isn&#8217;t in the actually written code.</p>
<h1>Using methods in Objective-C</h1>
<p>In Objective-C, you would create the same method like this:</p>
<pre lang="objc">-(int) someMathFunctionWithLength:(int)length width:(int)width;</pre>
<p>And call it like this:</p>
<pre lang="objc">[self someMathFunctionWithLength:5 width:10];</pre>
<p>There is definitely some explanation necessary here.</p>
<h2>The Method Prototype</h2>
<p>The &#8220;-&#8221; character at the begining of the function declaration says that this is an instance method.  This means that each instance of whatever class this is in, would have its own version of this method.  For example, if this was a method in a class that describes a cube, and it had an instance variable for height, and this method would return the volume of the cube based on the length and width put into this method, but the height stored as an instance variable, this is where you would use an instance method.</p>
<p>On the other hand, if this method was in a class that describes a square, and needs nothing from an instance of this class, you could make it a class method.  In this case, you would just use a &#8220;+&#8221; instead of the &#8220;-&#8220;.  These are similar (but not identical) to static methods in C++, Java, or C#.</p>
<p>The rest of the method prototype is the 2 parameters.  Unlike a normal C method, the first parameter is usually used as the name of the function, followed by its variable type, and what the parameter will be referred to internal to that method.  So for the first parameter, you would refer to the length variable just as &#8220;length&#8221; and not the &#8220;someMathFunctionWithLength&#8221; name.</p>
<h2>The Method Call</h2>
<p>Objective-C is a subset of C, so you can call methods similar to C if you really wanted, but that is not how it is meant to be done in Objective-C.  The method call here is called a &#8220;message&#8221;.  A message is what is written between the two square brackets.  The &#8220;self&#8221; keyword refers to the class this method is in.  In the more object oriented C-derived languages, like C++, Java, and C# there is keyword to refer to the class you are in, called &#8220;this&#8221;, and &#8220;self&#8221; basically is used the same way here.</p>
<p>Remember how I mentioned earlier that C method calls don&#8217;t really tell you what the parameters are without looking up the prototype?  This is one way Objective-C is quite helpful.  At a glance, you can tell that this math function wants a length, and a width, and you don&#8217;t need to look it up anywhere.  This does tend to give Objective-C rather long method names, but that description can be quite helpful.  The Xcode IDE has pretty good autocompletion, so the long method names are not too much of a hassle to write.</p>
<p>So, the rest of that call just shows you the name of the parameter, and after the colon is what you are sending as that parameter.  The parameters can be primitives or objects.  Each of these parameters is actually something called a &#8220;selector&#8221; in Objective-C.  I will get into the what that means in another post, but for now, just think of theme as the parameters for the function.</p>
<p>&nbsp;</p>
<p>Anyway, I hope this introduction to the wonderful world of square brackets has been helpful.  I plan to make a few more of these primer posts to describe some early and foundational ideas of Objective-C, particularly the ones that I found interesting or hard to get my head around.  Thank you for reading this blog post, and have a great day.</p>
<p>The post <a href="https://www.codingexplorer.com/objective-c-syntax-primer-1-methods/">Objective-C Syntax Primer 1:  Methods</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Interface Builder Issues</title>
		<link>https://www.codingexplorer.com/interface-builder-issues/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 19 Jul 2013 07:00:41 +0000</pubDate>
				<category><![CDATA[Interface Builder]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=40</guid>

					<description><![CDATA[<p>So, I have been doing several tutorials learning how to program iOS, and I have made a few mistakes. I then clean up those mistakes and try something else. I finish up the tutorial as they stated, start up the simulator, and then&#8230;. Crash. But how? I did everything the told me to do, their&#8217;s [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/interface-builder-issues/">Interface Builder Issues</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So, I have been doing several tutorials learning how to program iOS, and I have made a few mistakes. I then clean up those mistakes and try something else. I finish up the tutorial as they stated, start up the simulator, and then&#8230;. Crash. But how? I did everything the told me to do, their&#8217;s works, but mine won&#8217;t, what happened?!</p>
<p>Maybe it is from me being so new to interface builder, but so far, it has been kind of hit or miss with error reporting to me. My most recent issue with it, was I was trying to work with a Date Picker so that it would pop up from the bottom when I clicked a textfield, instead of the keyboard. I had to put it into an actionSheet, which is basically a drawer that pops up from the bottom of the screen, similar to how the keyboard shows up. I tried something from a stack overflow post that didn&#8217;t work at least for my situation, deleted all of the code, and tried something else. I finished coding that second way of doing it, loaded it up in the simulator, clicked on that textbox, and it crashed with the error: &#8220;unrecognized selector sent to instance&#8221;, and even with an exception breakpoint, it still pretty much showed up in the main, not very helpful. I tried to put up breakpoints, to stop it before any of my code executed there, but to no avail.</p>
<p><span id="more-40"></span>So what was the issue? As part of my first attempt, I had wired up an event for that textbox to an action in my Controller&#8217;s .h file. I had deleted that action from the header file, but did not unwire it from Interface Builder. I think it was on touch down, and so when it tried touch down, it looked for that method, couldn&#8217;t find it, and crashed. My breakpoints didn&#8217;t work because it never even got to them, thanks to this other event.</p>
<p>Now, I can understand it not automatically unwiring it when I delete the action, maybe I wanted to delete it and recreate it with a slightly different prototype, who knows? However, I would expect it to say SOMETHING. Hopefully a compiler error and just not let it compile since it is referencing something that doesn&#8217;t exist, but at least a warning, but nothing was there. Again, this may be my lack of experience with IB, but this seems like it would be rather important to show something wired to an action that doesn&#8217;t exist.</p>
<p>When recreating this error for this post, I noticed a few things that will help me identify things like this in the future, hopefully. For one, here is more of the error message:</p>
<p>-[CEBViewController notHere:]: unrecognized selector sent to instance</p>
<p>CEBViewController is the name of View Controller, obviously, and &#8220;notHere&#8221; is the dummy action I made for it, and then deleted in my .h and .m files. In the case of the my original program, the first thing was something like showActionSheet, so it was bit less obvious that it was one that was gone because my new action sheet method was something similar.</p>
<p>Also, I noticed that if I typed the action as a UITextField, this error did not happen, even when it was deleted. Only if I left it&#8217;s type as (id), it failed. Something I need to look into more.</p>
<p>Anyway, the moral of the story is, don&#8217;t trust IB to find all of your errors for you. It does, and has found other things I tried, deleted, but didn&#8217;t entirely clean up, and showed warnings, but apparently it does not every time. It may have a good reason, like that it could have it passed in, or expect it from inheriting or being inherited by something, I don&#8217;t know currently. But I do know that I have to be very careful to check everything when I clean up previous attempts to do something.</p>
<p>That&#8217;s all for today. Was the problem a newb one? You bet, and that&#8217;s I&#8217;m here to help others from falling into the same newb trap. Remember, keep your friends close, and your IB even closer.</p>
<p>The post <a href="https://www.codingexplorer.com/interface-builder-issues/">Interface Builder Issues</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>NSHelloWorld!</title>
		<link>https://www.codingexplorer.com/nshelloworld/</link>
		
		<dc:creator><![CDATA[Coding Explorer]]></dc:creator>
		<pubDate>Fri, 12 Jul 2013 08:25:52 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<guid isPermaLink="false">http://www.codingexplorer.com/?p=7</guid>

					<description><![CDATA[<p>Welcome to the Coding Explorer Blog. I am currently learning how to program apps for iOS. While I do have prior experience with C, I am pretty much learning Objective C from scratch.  I bought my first Mac near the beginning of February 2013, so I have owned a Mac for about 5 months now. [&#8230;]</p>
<p>The post <a href="https://www.codingexplorer.com/nshelloworld/">NSHelloWorld!</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Welcome to the Coding Explorer Blog.</p>
<p>I am currently learning how to program apps for iOS. While I do have prior experience with C, I am pretty much learning Objective C from scratch.  I bought my first Mac near the beginning of February 2013, so I have owned a Mac for about 5 months now. I have had the iPhone for about 3 years, so I&#8217;m not new to that. Nonetheless, I had not even looked at Objective C until the beginning of this year, so this is pretty much the ground floor.</p>
<p>The purpose of this blog, is for me to share what I&#8217;m learning as somebody fresh in this. That is also the reason for the name, basically I am exploring how to code for iOS, and I am taking those that want to come along with me. Am I bound to make mistakes and show a suboptimal way of doing things? More than likely, but everybody has to start somewhere. While I am scouring the web to learn how to program for iOS, I want to share what I find, so anticipate plenty of links to people who know how to do this better than I do.</p>
<p><span id="more-7"></span>I want to make this into a community of those that want to learn with me, and have this as an archive to those that come later to find that should hopefully help people when they are learning as well. So please, if there is a better, more efficient, cleaner, saner, or safer way to do anything I post here, please feel free to contact me about it. This effort will make the content of this blog more helpful to everybody which is exactly what I want to do.</p>
<p>I plan to help teach through multiple avenues. These will include:</p>
<ul>
<li>This blog. Standard blog posts will for simple, rather self-contained concepts, like explaining intricacies of some class I have recently learned about, links to other blogs, or general commentaries</li>
<li>Videos. More than likely hosted on YouTube. These will be tutorials to go step by step through doing something I want to teach. I was originally going to do this in the blog, but it ended up being a lot of screenshots, and I felt, why not have a video instead? These will also have accompanying blog posts for supplemental content, such as the code from the tutorial, links referenced in the video, and extra commentary when appropriate.</li>
<li>Social Media. This will be more like a college professor&#8217;s office hours. Contact me on twitter @CodingExplorer, and I&#8217;ll do what I can to help. Obviously since I&#8217;m still learning, I won&#8217;t be able to answer everything for a while, but I&#8217;ll do what I can.</li>
</ul>
<p>Thank you for reading this post, and stay tuned for more field notes from the Coding Explorer. Don&#8217;t worry, I don&#8217;t plan on being this corny too often&#8230; except for puns, expect those.</p>
<p>The post <a href="https://www.codingexplorer.com/nshelloworld/">NSHelloWorld!</a> appeared first on <a href="https://www.codingexplorer.com">Coding Explorer Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
