SimplePic app

Tuesday, July 22, 2014

A simple Swift program

Here is my first Swift program:

import Foundation
println ("256 256");
println ("255");

for i in 0...255 {
    for j in 0...255 {
        println("\(rand()%256) 255 \(j)");

It does an ASCII ppm file that is random in red, on in green, and ascending in blue.  It produces this image:

A few notes.  I had to add the import for it knew what rand() was.  The curly braces are required, which I like because it ends all those pointless arguments with yourself or others about whether to brace one line interiors of loops and the like.   I like that there is a "println" as I am tired of typing "\n".   This program took a while to write because xcode had a major silent hiccup complete with a misleading error message.   Stackoverflow to the rescue: when in doubt clean the code (menu option) and fully restart xcode.

1 comment:

Peter Shirley said...

Looks like I was semicolon happy. From the book: “Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. Semicolons are required, however, if you want to write multiple separate statements on a single line:”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.