Category: Programming

March 22nd, 2017 by admin

One unique feature of Swift is that it combines the features of a compiler with an interpreter. Xcode’s compiler lets you create apps you can distribute and sell while the Xcode interpreter, called a playground, lets you experiment with Swift commands to see how they work without having to create an entire project.

In the past, using playgrounds to learn Swift meant using a Macintosh, but Apple has released a free iPad app called Swift Playgrounds that lets you practice writing Swift code on an iPad. The only drawback is that you can’t compile Swift code on an iPad to create an actual program.

Still the latest release of Swift Playgrounds adds support for Simplified Chinese, which is the language used in mainland China. By offering Simplified Chinese language support, Swift Playgrounds can now cater to the entire mainland Chinese market.

While American schools mostly care only about price and buy Chromebooks instead of iPads, Chinese schools care more about preparing students for the future, and that means learning programming. By supporting Simplified Chinese, Swift Playgrounds can now tackle the huge educational market in China.

Swift Playgrounds is one example of a useful app that Chromebooks can’t duplicate. Apple’s future educational plans will likely include more educational apps to entice more schools, but also include more ways for teachers to customize and track student progress.

Remember, Apple recently acquired LearnSprout, a company that was dedicated to creating tools for teachers to measure and track progress of students using Apple products such as an iPad or Macintosh. By offering software features unavailable in rival products, Apple hopes to sell more iPads to the educational market.

Most likely, price will still be the deciding factor in American schools, but Chinese schools will likely look at the long-term benefits beyond initial pricing. That means Swift Playgrounds may soon be helping Chinese students learn programming and become future Apple developers.

Meanwhile, American students will be using much cheaper Chromebooks that lack educational tools such as Swift Playgrounds.

Whether Chromebooks or iPads are better for students will likely never be decided. What will be decided is that any school system that relies on iPads and Swift Playgrounds will likely create more programming students than a school system that relies on lower cost and simplicity regardless of how it affects student educational goals.

Swift Playgrounds is just one of many Apple features that can help tip schools in favor of the iPad for classrooms. It may not overcome the lower price of Chromebooks, but it’s a step in the right direction.

To learn more about Swift Playgrounds, click here.

Posted in Pre-teen and teenagers, Programming

February 27th, 2017 by admin

As much as Apple tries to make programming easier, the complexity of programming usually means Apple’s efforts actually wind up making programming harder. In the early days, programming was easy for anyone to master using a simple tool like HyperCard, which helped pave the way for visual interface design tools known as rapid application development (RAD) such as Visual Basic.

When Apple abandoned HyperCard, they offered Xcode in its place, which is a professional tool that novices will likely find way too intimidating. On top of trying to learn Xcode, you also have to learn a programming language such as Objective-C (way too confusing) or Swift, which is much easier to learn.

The huge problem with Swift isn’t the language but working with the cocoa frameworks that form the foundation of macOS, iOS, tvOS, and watchOS. You need to understand object-oriented programming along with protocols, and delegates. If all this sounds confusing, it is.

Perhaps one of the clumsiest solutions for solving problems lies with Core Graphics, Apple’s software framework designed to make animation possible. Learning to animate objects in a program means writing tedious Swift code to do the simplest things. Fortunately, there’s a tool that automates much of this process.

Called Core Animator, this program (ranging in cost up to $100 depending on the sales the company may offer at the moment) lets you visually animate objects using graphic files and timelines. Once you create the animation in Core Animator, you can export it into a Swift or Objective-C class file to add into a macOS or iOS project.

Because Core Animator lets you visually design animation and see it work, you don’t have to fumble with creating animation using mathematical formulas in Swift or Objective-C. Just as in the old days when programmers used to hand code user interfaces by writing commands, so does Core Graphics require you to write exhaustive Swift or Objective-C code to create animation.

RAD development tools let you design user interfaces visually and connect it to code. Core Animator lets you design animation visually and create code to add to an Xcode project.

Once you try Core Animator, you’ll never want to go back to hand-coding animation again in Swift or Objective-C because it’s too painful and tedious. Just watch the video below to see how simple it can be to use Core Animator.

While every project can use animation in its user interface, not everyone needs a program like Core Animator. However, animation can make your program stand out and add a little extra polish to your program and that may be worth the cost of Core Animator all by itself.

Posted in iOS, macOS, Programming

January 10th, 2017 by admin

If you look in the upper right corner on the menu bar of any Macintosh, you’ll see plenty of icons that represent volume control or access to your Time Machine backups. If you want to create a little utility that can be accessed through the menu bar, you need to create a menu bar app.

Unlike a regular macOS program, a menu bar app does not display a list of pull-down menu items, nor does a menu bar app display an icon on the Dock when it’s running. All a menu bar app needs to do is display an icon or menu title on the menu bar along with a menu of options for the user to choose from.

The first step to creating a menu bar app is to create a new macOS project Cocoa Application project where the “Use Storyboards” checkbox is clear. This will create a project that contains pull-down menus and a single window represented by a .xib file.

First, you can delete the .xib file or hide it. To hide the .xib window, click on it and choose View > Utilities > Show Attributes Inspector. Now clear the “Visible At Launch” check box. This keeps the window from appearing but still keeps it in your project in case you need it for any reason.

Once you’ve deleted or hidden the .xib window, the next step is to make sure the pull-down menus and program icon don’t appear on the Dock. To do this, click the Info.plist file in the Navigator pane to display a long list of various options.

Click on the last option and a + and – sign icon appears. Click this + icon to create a new line. In this new line, choose “Application is agent (UIElement)”.

Make sure the Type for this line is Boolean and its Value is YES. This option will keep the program’s icon from appearing on the Dock when running and keep its pull-down menus from appearing on the left side of the menu bar at the top of the screen.

Once you’ve hidden the window, pull-down menus, and Dock icon, the last step is to write Swift code to create the menu bar title and a pull-down menu.

Open the AppDelegate.swift file and underneath the class AppDelegate line, add the following:

var item : NSStatusItem? = nil

This creates the object that will appear on the status bar. Inside the applicationDidFinishLaunching function, you need to assign this “item” object an actual value:

item = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)

The above code creates an object, but we still need to display it on the menu bar. One way to display the menu bar is as an icon (which will be covered in a future blog post). A second way is as text, which you can create by defining its title property like this:

item?.title = "MyMenu"

The string assigned to the title property can be anything you want, but keep it short and descriptive.

After you’ve created a menu title, the next step is to create a pull-down menu list. To do this, you need to create an NSMenu object and then fill it with titles like this:

let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Option 1", action: #selector(AppDelegate.testMe), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Quit", action: #selector(AppDelegate.quitMe), keyEquivalent: ""))
item?.menu = menu

To define each item in the pull-down menu, you need to use the addItem command. The title property defines the command that appears on the menu and the #selector identifies the function that runs when the user clicks on that menu item.

The keyEquivalent property lets you define a letter that represents a shortcut keystroke for accessing the command. In general, it’s best to leave it blank because it takes more time to use the keystroke shortcut than it will to simply click on the menu item they want.

Finally, you need to assign your NSMenu object to your menu bar’s menu property.

At this point, your pull-down menus will appear but won’t do anything because you still need to write functions that run when the user clicks on a particular menu item.

In the above example, the two #selector commands are looking for a testMe and a quitMe function (although you can choose any name you wish). So if you used the above code, the two functions you’d need to create are as follows:

    func testMe() {
        print ("It works!")
    }
    
    func quitMe() {
        NSApplication.shared().terminate(self)
    }

The NSApplication.shared().terminate(self) command simply quits the program.

The complete code of the AppDelegate.swift file should look like this:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    var item : NSStatusItem? = nil
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        
        item = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
        
        //Displays text on menu bar
        item?.title = "TestMe"
        
        // Defines function to run when the user clicks on the text on menu bar
        //item?.action = #selector(AppDelegate.testMe)
        
        let menu = NSMenu()
        menu.addItem(NSMenuItem(title: "Option 1", action: #selector(AppDelegate.testMe), keyEquivalent: ""))
        menu.addItem(NSMenuItem(title: "Quit", action: #selector(AppDelegate.quitMe), keyEquivalent: ""))
        item?.menu = menu
    }
    
    func testMe() {
        print ("It works!")
    }
    
    func quitMe() {
        NSApplication.shared().terminate(self)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }


}

If you choose Product > Run, you should see the menu text “TestMe” appear on the menu bar. If you click on it, a pull-down menu appears displaying “Option 1” and “Quit”. If you click Option 1, the program prints “It works!” in the Debug area of the Xcode window. If you click Quit, your program stops running.

This simple project demonstrates how to create a simple menu bar app that displays a menu title (“TestMe”) on the menu bar. When the user clicks on this menu title, a pull-down menu appears with two options.

You can download the complete MenuBarApp project here.

Posted in macOS, Programming, Xcode

November 29th, 2016 by admin

Cross-platform development is the Holy Grail of programming because the idea is to write one set of code that can run on multiple platforms. The reality is that such cross-platform development always comes at a price.

The first price is that cross-platform development can’t take full advantage of the features of any particular platform. The moment you use specific operating systems, your code is no longer completely cross-platform.

It’s still far simpler to modify a small chunk of code rather than rewrite an entire project from scratch, but cross-platform development often targets the lowest common denominator of each operating system and often lags behind supporting the latest feature of any particular operating system.

Of course the greatest appeal of cross-platform development is writing one program to run on multiple platforms. If you’re willing to accept limitations in return for greater productivity, then you’ll likely want to look at cross-platform development tools.

Java represents the so-called “write once, run everywhere” mantra of cross-platform development. While you can technically write Java code to run on multiple platforms, the reality is that Java never completely fulfilled its promise.

One huge advantage of Java is that it’s the main programming language for Android and can also be ported to iOS, so if you’re looking for a mobile cross-platform solution, Java may be the answer.

Another possible solution is Xamarin, which lets you use C# code to create Android and iOS apps as well. Best of all, Xamarin is free and can run on either Windows or macOS. If you’re already a Windows developer familiar with C#, Xamarin is an attractive solution.

Another cross-platform took is NSB/App Studio that lets you use JavaScript or BASIC to create Android or iOS apps. NSB/App Studio is offered on a subscription basis that costs as little as $15 a month or up to $900 a year depending on which features you want.

For desktop cross-platform capability, there’s Xojo, which offers a Visual Basic-like development tool for creating Windows, macOS, Linux, and iOS apps. Android support is coming soon and the price ranges from $99 to target a single operating system such as Windows or macOS, up to $299 to write iOS apps. For $699 or $1,999 you get more features.

One of the strangest cross-platform tools is LiveCode, which lets you create Windows, macOS, Linux, iOS, and Android apps. LiveCode is based on Apple’s old HyperCard card and stack metaphor that uses a unique programming language that closely resembles English sentences.

As a result, LiveCode syntax tends to be wordy and far different than traditional programming languages, but for novices, this can actually be a benefit. The huge drawback with LiveCode is their ever-increasing price annual price.

Initially LiveCode charged $299 a year, then $499 a year, then $699 a year, and now they’re up to $999 a year. This effectively prices them out of the reach of most people and insures that LiveCode will never become a popular option.

Cross-platform tools are great for tackling multiple operating system markets at once, but beyond Java and Xamarin, there may not be much of a market for cross-platform skills in specific tools like NSB/App Studio, Xojo or LiveCode. If you learn one of these tools, be sure to learn a more general programming language like Java or Swift as well.

Cross-platform tools aren’t the magic bullet for writing software but they do offer some advantages in writing a project once and running (and selling it) in multiple markets. Just weigh the advantages against the drawbacks and maybe a cross-platform tool will be the solution you’re looking for.

Posted in LiveCode, Programming, Xojo

November 26th, 2016 by admin

Apple doesn’t always make life easy. If you want to write Touch Bar macOS programs in Xcode, you need the latest versions of macOS Sierra 10.12.1 and Xcode 8.1. However, the latest macOS Sierra update you need isn’t the one found in the Mac App Store. Instead, you have to download the latest macOS Sierra update directly from Apple at this link:

https://support.apple.com/kb/dl1897?locale=en_US

Until you download and install this latest macOS Sierra update, you won’t be able to see the Touch Bar simulator in Xcode 8.1. This is a simple problem made more complicated by the fact that you have to download the macOS update direct from Apple instead of the App Store.

Hopefully by the time you read this, Apple will have put the latest macOS update on the App Store but until then, this macOS update direct from Apple is the missing ingredient needed to add Touch Bar support to Xcode 8.1

Posted in Programming, Xcode

November 1st, 2016 by admin

If you’re familiar with a language like C, you may already know how to create a loop that counts. In Objective-C, such a counting loop might use the for loop like this:

for (int i = 1; i <= 10; i++)
{
    // code here
}

T

he typical for loop consists of three parts. First, you need to specify a starting number. Second, you need to specify the ending number. Third, you have to define how to increment the counting number. Typically you would increment by 1 by using the ++ operator.

If you look at this code carefully, you can see plenty of redundancy. In the above Objective-C for loop example, you define a counting variable (i) three times. Since most for loops increment by 1, it’s also cumbersome to keep using the ++ operator all the time. That’s why Swift simplifies the typical for loop by using a for-in loop instead such as:

for i in 0...10  {
   // code here
}

Notice that the Swift for-in loop simply defines a counting variable once and the starting and ending points in a simpler form. That means less code to type and less possibility of making minor syntax mistakes that even professionals make all the time.

However, the Swift for-in loop does lack one feature. By default, the for-in loop increments by 1 so you don’t need to use the ++ operator. Yet what made the typical for loop versatile in C was that you could increment by other numbers besides 1 such as counting by 3 or 5 like this:

for (int i = 1; i <= 10; i = i + 5)
{
    // code here
}

In Swift, you can also count by increments but it’s not as quite straightforward as you might think. To count by increments other than 1, you have to use the where keyword along with the modulus (%) operator such as:

for i in 0...10 where i%3 == 0  {
    print (i)
}

This Swift code says count from 0 to 10 but only where the counting variable (i) divided by 3 equals 0. That essentially means to count in increments of 3. Replace the number 3 by whatever counting increment you want and you can now make the Swift for-in loop count by increments other than 1.

Although Swift simplifies coding over C, this clumsy for-in where loop is one example where Swift actually makes counting in different increments less intuitive.

A far more intuitive but wordier solution is to use the while loop to increment by values other than 1 such as:

var i = 0
while i <= 10 {
    print (i)
    i = i + 3
}

This while loop requires initializing a value first, then specifying an ending point, then incrementing the counting variable inside the while loop itself. If you fail to increment the counting variable inside the while loop, you risk creating an endless loop.

Although this mistake is easy to fix, it’s also easy to make, which means the while loop is a clumsier alternative to the for-in loop.

Now that you know how to count in increments other than 1, you can use this solution easily in your own Swift projects.

Posted in Algorithms, Programming

September 21st, 2016 by admin

You might think declaring variables would be something simple to do in Swift and it is. The problem comes with the different ways to declare variables, mostly based on older programming languages.

Here’s the traditional way to declare a variable in an older language. First, you declare a variable and its data type. Second, you give that variable a value. In Swift, this two-step method of declaring variables looks like this:

var name : String
name = "John Doe"

One problem with this two-step method is if you forget to define a value to a variable and then later try to use that variable, your program could crash because the value of that variable is undefined.

For a more advanced way to declare variables, use just one step. Declare the variable as a particular data type and then assign a value to it right away. In Swift, this second way to declare a variable looks like this:

var name : String = "John Doe"

By following this practice of assigning a value to a variable as soon as you declare it, you minimize the risk of leaving a variable without a specific value, even if that value is only temporary. However, declaring a variable name, its data type, and its value is cumbersome. That’s why Swift offers a third way to declare variables and assign them values by simply eliminating the data type.

Essentially, data types mean the variable can hold a number or a string. A number could be an integer or a decimal number. So it’s often much simpler to use this third method of Swift of eliminating the data type completely.

In Swift, this is called inferring the data type, which means you just need to assign a value to a variable and Swift infers the data type like this:

var name = "John Doe"

Any time you assign a string to a variable, Swift assumes the variable data type is String.

Any time you assign an integer to a variable, Swift assumes the variable data type is Int.

Any time you assign a decimal number to a variable, Swift assumes the variable data type is Double.

Sometimes it’s better to specify exactly the data type you want to use. For example, if precision isn’t that important, then just use a Float data type for a decimal number instead of Double. Since Float data types store less precision, they take up less memory as well.

So the three ways to declare a variable are:

  • Declare a variable as a data type, then assign a value to that variable on another line
  • Declare a variable as a data type, then assign a value to that variable on the same line
  • Declare a variable by assigning a value to that variable on the same line

For simplicity, the third method of letting Swift infer the data type is shortest and easiest. For clarity, the second method of declaring a data type and assigning a value to it is clearer. In general, avoid the first method of declaring variables because it’s too easy to forget to assign a value to a variable by mistake.

Even something as simple as declaring a variable in Swift takes thought. If you think ahead, you can always make programming easier in the long run.

Posted in Programming

August 18th, 2016 by admin

The two basic data types for variables are strings and numbers. Numbers can be integers (Int) or decimal numbers (Float or Double). When declaring a variable as a decimal number, you have to choose between Float and Double.

The big difference between the two is that Float variables can only hold seven digits of precision while Double variables can hold twice that number.

Suppose you declare a Swift Float variable with a long decimal value. Swift simply cuts off the value after seven digits like this:

var floatVar: Float = 0.123456789123456789      // 0.1234568

But if you declare a Swift Double variable, it retains more than twice the precision (hence the name Double) like this:

var doubleVar: Double = 0.123456789123456789    // 0.1234567891234568

(You may need to scroll left and right to see all of the above code.)

So the simple lesson is that if you’re going to use decimal numbers and need precision, use Double instead of Float data types.

If you declare a variable to hold a decimal number without specifying the data type, Swift uses the Double data type.

For clarity, it’s generally best to stick with Double data types since it’s common for programmers to declare variables to hold decimal numbers without defining the data type like this:

var doubleVar = 0.123456789123456789    // 0.1234567891234568

By always using Double data types, you avoid needing to convert Float variables to Double or vice versa. Just use Double unless you want to use Float to save memory, which shouldn’t be a problem except in rare cases.

Remember: Use Double data types, not Float.

Posted in Programming

July 13th, 2016 by admin

What makes a good programmer? Most people think its math skills but the answer might involve musical talent.

Albert Einstein once said, “The greatest scientists are artists as well.” The idea that art and science are distinct and separate is probably the single most damaging belief in limiting both artists and scientists. That’s why the evidence claiming musical talent leads to better coding is a welcome change.

Because of their performance background, attention to detail, and innate need to perfect their parts, musicians tend to be analytical, logical and methodical—skills that the best coders also possess. “There seems to be a high correlation between musical ability and reasoning skills,” Terry Skwarek, the director of SharePoint administration at DePaul University. “It has to do with recognizing and manipulating patterns. That happens in music and in programming.”

Not only is music analytical, but it’s also creative. That’s why musicians can often visualize the performance of their code in the same way that they can visualize the sound of musical notes.

So if you think schools are emphasizing too much math and science at the expense of the arts, you’re probably right. Schools should keep arts and science in equal emphasis because the arts influence science and science influences the arts. By keeping both art and science in the proper perspective, tomorrow’s programmers might be artists as well.

To learn more about the link between music and programming, click here.

Posted in Programming

May 2nd, 2016 by admin

Your app can display a web page by using the Web View object on your user interface and then by writing three lines of code. So first, place a Web View on your user interface and give it a unique name such as webView, although the exact name isn’t important.

Next, create a variable or constant using any name you wish. Then set this variable/constant to a string that defines the complete web site address like this:

        // The web address must be https:// and not just http://
        let showURL = NSURL(string: "https://www.apple.com")

The only restriction is that the web site address must use https:// and not just plain http:// or else it won’t work.

After creating a variable/constant to represent the web site address, you need to create a second variable/constant to request the web site address, known as a URL:

        let requestThis = NSURLRequest(URL: showURL!)

Finally you need to use the loadRequest method on your Web View to request a particular web site domain address:

        webView.loadRequest(requestThis)

So the complete code to work with a Web View object on your user interface looks like this:

        // The web address must be https:// and not just http://
        let showURL = NSURL(string: "https://www.apple.com")
        let requestThis = NSURLRequest(URL: showURL!)
        webView.loadRequest(requestThis)

Just paste a different string for the web site address and you’ll be able to display a different web site. Remember, make sure the web site address uses https:// and also make sure the web site is optimized for mobile devices so it adapts to the smaller screen of an iPhone or iPad.

Posted in Programming, User Interface, Xcode

HTML Snippets Powered By : XYZScripts.com