Archive for May, 2016

Float-initialized UIColors

Discovered on the Swift-User list that UIColor in the most recent May 3rd toolchain supports initializers for both Float and CGFloat. Which is odd:

Screen Shot 2016-05-11 at 8.33.08 AM

You can see both initializers at the bottom of the screen shot.

Bit of a problem because Xcode complains about an “Ambiguous use of init(red:green:blue:alpha:)”. No kidding. So right now, you can start casting everything, e.g.

let color = UIColor(red: CGFloat(0.5), green: CGFloat(0.5), blue: CGFloat(0.5),  alpha: CGFloat(1.0))

Or you can do something really stupid like this:

extension Double {
    var cg: CGFloat { return CGFloat(self) }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()        
        let c = UIColor(red: 0.5.cg, green: 0.5, blue: 0.5, alpha: 0.5)
    }
}

It works but ew.

So here’s my question: who ever uses Float with UIColor to begin with and why did this pop up in the latest build? Is it part of the Cocoa auto-migration thing? And do you think I should just go ahead and file a bug?

Update: Bug filed. SR-1479 Resolved as dupe. ūüôā

This week’s Swift Evolution reviews

A handful of reviews that are launching tomorrow:

  • May 10…16, 2016¬†SE-0041: Updating Protocol Naming Conventions for Conversions¬†The Swift standard library includes slightly north of eighty protocols. Of these, about 15% concern themselves with type initialization and conversion. This proposal assigns specific conventional suffixes to these tasks.
  • May 10…16, 2016¬†SE-0075: Adding a Build Configuration Import Test¬†Testing for imports enables you¬†to test for API availability before use.
  • May 10…16, 2016¬†SE-0081: Move¬†where¬†clause to end of declaration¬†This proposal suggests moving the¬†where¬†clause to the end of the declaration syntax, but before the body, for readability reasons. It has been discussed at length on the following swift-evolution thread. +1!!!
  • May 10…16, 2016¬†SE-0083: Remove bridging conversion behavior from dynamic casts¬†Dynamic casts using¬†as?,¬†as!, and¬†is¬†are currently able to dynamically perform Cocoa bridging conversions, such as from¬†String¬†to¬†NSString¬†or from an¬†ErrorProtocol-conforming type to¬†NSError. This functionality should be removed to make dynamic cast behavior simpler, more efficient, and easier to understand. To replace this functionality, initializers should be added to bridged types, providing an interface for these conversions that’s more consistent with the conventions of the standard library.
  • May 10…16, 2016¬†SE-0084: Allow trailing commas in parameter lists and tuples¬†Swift permits trailing commas after the last element in array or dictionary literal. This proposal extends that to parameters and tuples.

Swift 3.0 Release Process

The first Swift  3 developer preview will drop this week on 12 May 2016. Big news for everyone getting ready to start migrating.

Posted on the Swift.org blog:

Swift 3.0 is a major release that is not source-compatible with Swift 2.2. It contains fundamental changes to the language and Swift Standard Library. A comprehensive list of implemented changes for Swift 3.0 can be found on the Swift evolution site.

Swift 3.0 is also the first release to include the Swift Package Manager. While the Swift Package Manager is still early in its development, it supports the development and distribution of cross-platform Swift packages. The Swift Package Manager will be available on both Darwin and Linux.

For Linux, Swift 3 will also be the first release to contain the Swift Core Libraries.

Developer previews will start rolling out soon, with an expected released date for Swift 3.0 in late 2016-ish. If you haven’t been using Xcode’s new toolchain selection feature yet, you’ll find it under the main Xcode menu:

Screen Shot 2016-05-09 at 2.35.37 PM

Although the Swift team has been putting out snapshots every few¬†weeks, previews will arrive less often — between 4 and 6 weeks per release. “They will be partially driven by the volume of change going into¬†master¬†and how much time is needed to stabilize a developer preview branch.”

Further details about contributions, pull requests, and affected repositories are at the Swift.org blog post.

World War String

Swift Evolution is engaged in a war over the multi-line string. While this conversation dates back some time, it has progressively grown more heated in recent days.

I just want closure. I’m more interested in closure¬†than perfection.¬†My favorite solution¬†to date is the Holdsworth/Royal-Gordon approach:

7bc90d68-0fc1-11e6-8b15-2b9ae678929a

It is simple. It does not disallow pasted text, with the proper support from Xcode. It can theoretically be applied (and removed) mechanically as you can currently do with commenting.

Its parsing/lexing is simple and already Holdsworthed. (In theory, everything that can be conceptualized in Xcode is nearly Holdsworthed.) And it probably wouldn’t be hard to request an Xcode modification similar to Comment/Uncomment¬†that indents and inserts quotes and toggles back to left-alignment at the initial quote mark.

That the debate rages on remains a mystery to me.

Speaking of Xcode and its commenting support, I am still waiting for better Apple-originated structured documentation commenting. As is, it’s particularly ridiculous to try to introduce¬†sample code blocks without manually spacing¬†and adding in third slashes, let alone proof for spell checking and grammar. But that’s probably a rant better left for another blog post.

For today, I support the Holdsworth/Royal-Gordonians. Viva la quoted resistance!

Playground Secrets: Update and new tricks

A big thanks to James Dempsey for tracking down not one but two new playground markup keywords. In addition to the new Xcode 7.3 experiment, note, and important markup, you can now add example and callout.

The example keyword adds a well-formated example that introduces a section that demonstrates a new concept:

Screen Shot 2016-05-03 at 9.46.55 AM

The callout in constrast lets you use any title you want, enabling you to add flexible tips, warnings, cautions, trivia, and so forth.

/*: - callout(Trivia): The superscript dot over a lowercase (or miniscule) letter i is called a [tittle](https://en.wikipedia.org/wiki/Tittle) and is considered an integral part of the letter's glyph. ![tittles](tittles.png) */

Screen Shot 2016-05-03 at 10.04.43 AM

One more great find in Xcode 7.3, is that the fuzzy auto complete pop-up now incorporates documentation markup so you can view the description of any selected item:

Screen Shot 2016-05-03 at 8.17.02 AM

I’ve updated both Documentation Markup and Playground Secrets to include the new tech features and expanded coverage with regard to callouts, Swift 3 upcoming features, and more.

Both books are available at iTunes and LeanPub. Your continued support enables me to keep revising these works and buy an occasional cup of coffee. Thank you!

Despite ridiculous technological difficulties with Pearson’s pilot Content Update Program, I am still pushing ahead with incorporating the Swift 2.2 changes into the Cookbook. (Pearson, if you haven’t heard, laid off about half or more of their workforce, has shut down ¬†marketing, and is likely to close its developer library program.)

Despite these difficulties, I think the Cookbook (the name was chosen long before I started writing, and no, I couldn’t change it when it became clear that Swift was still evolving) is a darned nice addition to any¬†development library.

I think you’ll like the book a lot if you can get past the title. It’s full of practical, sensible how-to and is perfect for anyone who has finished Apple’s tutorial and wants to start with real development.

Thank you for buying my books and helping me to support my family.

The great space-delimited comma war

From an intense disagreement this afternoon:

func foo<T: protocol<A,B>>(x: T)

vs

func foo<T: protocol<A, B>>(x: T)

Clearly the latter wins. But why? Because orthography matters.

Strunk writes, “omit needless words”. But Strunk did not write, “omit needless keystrokes”. Space-delimited commas offer semantic and syntactic separation between two related items. It follows the convention commonly used in mathematics.

A space-delimited comma supports natural language precedent allowing the eye to scan each token as a distinct entity. It serves as a pause signal for the code reader, allowing mental differentiation between the two elements (in this case, dual protocols).

Without that pause, the two protocols blend into an undifferentiated mass, especially as they are surrounded by the angle brackets used to construct the protocol conformance and type parameter. Allowing space to breathe creates a more readable product, and is to be preferred to its spaceless alternative[1].

[1] This advantage is to be conveyed to all users, whether or not they are Canadian in origin.

Dear Erica: Why doesn’t NSLog support Swift objects

Dear Erica, when I try to run the following code in a playground, Xcode dies, with the complaint “error: ‘NSLog’ is unavailable: Variadic function is unavailable¬†NSLog(“%@”, Foo())¬†Foundation.NSLog:2:13: note: ‘NSLog’ has been explicitly marked unavailable here“. What gives?

import Foundation
class Foo {}
NSLog("%@", Foo())

Your first problem is that Foo is not an NSObject. ¬†If you subclass Foo from NSObject, the error goes away and the log statement outputs “<__lldb_expr_24.Foo: 0x7fc9d2920210>“. Still not exactly what you’re looking for, I know.

The reason is that in our discussion going back and forth I know you wanted to use CustomDebugStringConvertible with NSLog and the way you make that happen is by using normal string interpolation with NSLog:

class Foo: CustomDebugStringConvertible {
    var debugDescription: String {return "Superfoo!"}
}

NSLog("\(Foo())")

Swift and NSLog aren’t really set up to do the format string interoperation you were looking for. However, if you’re bound and determined to do so, there¬†is¬†a solution:

class Bar: NSObject {
    override var description: String {return "Superbar!"}
}

NSLog("%@", Bar())

In this case, instead of trying to conform to CustomDebugStringConvertible, you override the built-in NSObject property to get the custom output you were looking for. Implementing description¬†(OS X 10.10 and later) returns a string that “describes the contents of the receiver”.¬†NSLog can then use this result to create a textual representation of your object, which can be used in a formatted string.

2016-05-02 14:12:43.106 Untitled Page 3[5161:524832] Superfoo!
2016-05-02 14:12:43.107 Untitled Page 3[5161:524832] Superbar!

Like in Swift native classes, NSObject also supports a debug variation (debugDescription, OS X 10.8 and later), which is preferred for presentation in the debugger.

Survival of the Swiftest: What’s up in Swift Evolution

Accepted

SE-0068: Expanding Swift Self to class members and value types is accepted with modifications:

The review of SE-0068: “Expanding Swift Self to class members and value types” ran from April 20…25, 2016. A subset of the proposal has been *accepted*:

This proposal had light discussion in the community review process, but the core team heavily debated it.  It includes two pieces:

1. Expanding the existing support for Self to work in value types, and in the bodies of classes.
2. Replacing the x.dynamicType expression with x.Self, a purely syntactic change that eliminates the ‚ÄúdynamicType‚ÄĚ keyword.

The core team has accepted the first half for this proposal. ¬†This allows the use of ‚ÄúSelf‚ÄĚ as shorthand for referring to the containing type (in the case of structs, enums, and final class) or the dynamic type (in the case of non-final classes). ¬†Most of the discussion in the core team centered around whether people familiar with the former behavior would be surprised by the (more general) behavior when using it in a class, but they came to agree that this is actually a simple and general model, and a helpful point of consistency.

In contrast, there are still a number of concerns with rebranding x.dynamicType as x.Self. ¬†This may (or may not) be the right ultimate direction to go, but it should be split out of this proposal. ¬†There is another outstanding proposal that would eliminate the ‚ÄúType.self‚ÄĚ syntax as being necessary, and the core team would like to resolve that discussion before tackling x.dynamicType.

A¬†third part of the proposal, already removed, which would introduce #Self, to be replaced at compile time with the calling context for use in return types, variable types, and debug statements, will also be deferred until after the “Type.self” syntax is settled.

SE-0065: A New Model for Collections is accepted.

We propose a new model for Collections wherein responsibility for index traversal is moved from the index to the collection itself. For example, instead of writing i.successor(), one would write c.index(after: i). We also propose the following changes as a consequence of the new model:

  • A collection’s¬†Index¬†can be any¬†Comparable¬†type.
  • The distinction between intervals and ranges disappears, leaving only ranges.
  • A closed range that includes the maximal value of its¬†Bound¬†type is now representable and does not trap.
  • Existing ‚Äúprivate‚ÄĚ in-place index traversal methods are now available publicly.

SE-0066: Standardize function type argument syntax to require parentheses [ACCEPTED]¬†in review to 5/2. “This proposal suggests that we simply eliminate the special case and require parentheses on all argument lists for function types.” I’m strongly for this one.

SE-0067: Enhanced Floating Point Protocols [ACCEPTED] enters Review #2 with incorporated feedback to 4/29. “Revision 2 reintroduces some of the details of the¬†Arithmetic¬†protocol from earlier drafts of this proposal, but as methods in the¬†FloatingPoint¬†API, with the goal of reducing the number of overloads for basic operations. This change was requested by some members of the core langauge team. Revision 2 also incorporates a number of suggestions from the review list and corrects some typos; thanks especially to Xiaodi Wu for thoughtful feedback.”

SE-0070: Make Optional Requirements Objective-C-only [ACCEPTED]¬†in review to 5/3. “Swift currently has support for “optional” requirements in Objective-C protocols, to match with the corresponding feature of Objective-C. We don’t want to make optional requirements a feature of Swift protocols (for reasons described below), nor can we completely eliminate the notion of the language (for different reasons also described below). Therefore, to prevent confusion about our direction, this proposal requires an explicit ‘@objc’ attribute on each¬†optional¬†requirement to indicate that this is an Objective-C compatibility feature.”

SE-0071: Allow (most) keywords in member references¬†[ACCEPTED] in review to 4/29. “The¬†Swift API Design Guidelines¬†consider enum cases as values that use the lowerCamelCase naming conventions. This means that case names that previously did not conflict with keywords (such as¬†Default,¬†Private,¬†Repeat) now cause conflicts, a problem that is particularly acute when the naming conventions are applied by the Clang importer (per¬†SE-0005). To mitigate this issue, this proposal allows the use of most keywords after a “.”, similarly to how¬†SE-0001¬†allows keywords are argument labels.”

SE-0061: Add Generic Result and Error Handling to autoreleasepool()¬†[ACCEPTED]¬†in review to 4/26. Not to be confused with Generic Result and Error Handling in Deadpool. “The¬†autoreleasepool¬†function in the standard library does not currently support a return value or error handling, making it difficult and error-prone to pass results or errors from the body to the calling context.”

SE-0069: Mutability and Foundation Value Types [ACCEPTED]¬† in review to 5/4. This one gives¬†“mutability when you need it” to wrap Foundation variations invisibly to Swift use.

SE-0017: Change Unmanaged to use UnsafePointer [ACCEPTED] in review to 5/3. “The standard library¬†Unmanaged<Instance>¬†struct¬†provides a type-safe object wrapper that does not participate in ARC; it allows the user to make manual retain/release calls”. SE-0017 proposes to replace the use of¬†of¬†COpaquePointer¬†with¬†UnsafePointer<Void>¬†and¬†UnsafeMutablePointer<Void> in the¬†Unmanaged¬†API.

SE-0052: Change IteratorType post-nil guarantee [ACCEPTED] in review to 5/3. “Currently, the documentation for¬†IteratorType.next()¬†has the precondition that when calling¬†next(), no preceding call to¬†next()¬†should have returned¬†nil, and in fact encourages implementations to raise a¬†preconditionFailure()¬†for violations of this requirement. However, all current 27¬†IteratorType¬†implementations in the standard library return¬†nilindefinitely. Many users are likely unaware of the precondition, expecting all iterators to return¬†nil¬†indefinitely and writing code that might rely on this assumption. Such code will usually run fine, until someone does in fact pass in an iterator not repeating¬†nil¬†(it’s a silent corner case).”

SE-0032: Add find method to SequenceType [ACCEPTED]¬†¬†in review to 5/3. I have personal issues with SequenceType, namely that there may non-terminating sequences. My issues have nothing to do with this proposal, which Lily clarifies: “I have seen people write code like¬†seq.lazy.filter(predicate).first, but this doesn’t actually work lazily because¬†.first¬†is only a method on¬†Collection, which means the call to¬†filter()¬†ends up resolving to theSequence.filter()¬†that returns an Array instead of to¬†LazySequenceProtocol.filter()¬†that returns a lazy sequence. Users typically aren’t aware of this, which means they end up doing a lot more work than expected.”

SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib [PARTIALLY ACCEPTED: parts returned for bikeshedding over the naming] in review to 5/3.¬†Love the proposal.¬†Hate the name mismatch. Either prefix/suffix or take/drop makes more sense to me. Worse, the beautiful and fairly obvious¬†iterate is under fire and may become something like “ice ice baby” or “unfold(_:applying:)“. This review gets all the +1s,¬†except for the naming.

SE-0072: Fully eliminate implicit bridging conversions from Swift [ACCEPTED] runs to 5/2. “In Swift 1.2, we attempted to remove all implicit bridging conversions from the language. Unfortunately, problems with how the v1.2 compiler imported various un-annotated Objective-C APIs caused us to scale back on our ambitions. In the interest of further simplifying our type system and our user model, we would like to complete this work and fully remove implicit bridging conversions from the language in Swift 3.”

In Review

  • SE-0060: Enforcing order of defaulted parameters¬†In review to 5/9. I vote no. Details at link.
  • SE-0073: Marking closures as executing exactly once in review to 5/9. “This proposal introduces an optional¬†once¬†argument to the¬†@noescape¬†attribute. The¬†@noescape(once)¬†attribute enforces that the closure does not escape, and that it is run exactly once on any code path returning from the function. For clients, it allows the compiler to relax initialization requirements and close the gap between closure and “inline code” a little bit.”
  • SE-0074: Implementation of Binary Search functions in review 5/9. “Swift does not offer any way to efficiently search sorted collections. This proposal seeks to add a few different functions that implement the binary search algorithm.”
  • SE-0076: Add overrides taking an UnsafePointer source to non-destructive copying methods on UnsafeMutablePointer in review to 5/9. “UnsafeMutablePointer includes several methods to non-destructively copy elements from memory pointed to by another UnsafeMutablePointer instance. I propose adding overloads of these methods to UnsafeMutablePointer that allow an UnsafePointer source.”
  • SE-0078: Implement a rotate algorithm, equivalent to std::rotate() in C++¬†in review to 5/9. “There are three different versions of the rotate algorithm, optimized for collections with forward, bidirectional, and random access indices. The complexity of the implementation of these algorithms makes the generic rotate algorithm a perfect candidate for the standard library.”
  • SE-0080: Failable Numeric Conversion Initializers in review to 5/9. “Swift numeric types all currently have a family of conversion initializers. In many use cases they leave a lot to be desired. Initializing an integer type with a floating point value will truncate any fractional portion of the number. Initializing with an out-of-range value traps. This proposal is to add a new family of conversion initializers to all numeric types that either complete successfully without loss of information or throw an error.”

Awaiting Scheduling

Like my posts? Consider buying a book or two. Thanks!