[swift-evolution] Proposal: Namespaces

T.J. Usiyan griotspeak at gmail.com
Fri Dec 11 04:39:40 CST 2015


Namespaces
Author(s): TJ Usiyan

Introduction

A `namespace` keyword for swift hold related global variables.

Motivation

We often want to collect related variables which do not, for whatever
reason, fit neatly into a type provided by Swift. Importing Objective C
'magic strings' as Joshua Sullivan does [here] is one such example. The
solution he arrives at is a `struct` type with many type variables and no
fields.
struct NotificationNames {
 static let userDataChanged = "UserDataChangedNotificationName"
 static let receivedAlert = "ReceivedAlertNotificationName"
 static let peanutButterJellyTime =
"ItsPeanutButterJellyTimeNotificationName"
}

Users of this API are not meant to create instances of this type, yet it is
still possible. A solution to this is to use an `enum` without cases.

enum NotificationNames {
 static let userDataChanged = "UserDataChangedNotificationName"
 static let receivedAlert = "ReceivedAlertNotificationName"
 static let peanutButterJellyTime =
"ItsPeanutButterJellyTimeNotificationName"
}

No instances of the `enum` can be made. That this inability to create an
instance is intentional is only conveyed via the type system.

Proposed solution

Clarity would be greatly improved if we could use `namespace` as a synonym
for an enum with no cases. This would allow us to avoid repetition of
`static` as well.

namespace NotificationNames {
 let userDataChanged = "UserDataChangedNotificationName"
 let receivedAlert = "ReceivedAlertNotificationName"
 let peanutButterJellyTime = "ItsPeanutButterJellyTimeNotificationName"
}

Detailed design

Namespaces can be represented in the type system as enums. All variables
declared in a namespace's scope would be type variables.

Impact on existing code

This is an additive change and, as such, should not break any existing
code. Though it doesn't matter, this addition could possibly attain ABI
compatibility if namespaces are represented as enums without cases.

Alternatives considered

Don't implement namespaces. Developers could continue(begin?) using an
empty enum to hold type variables.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151211/0ea5954f/attachment.html>


More information about the swift-evolution mailing list