[swift-evolution] Object declarations

Marc Knaup marc at knaup.koeln
Fri Dec 11 19:48:18 CST 2015


@Andrey

   - Note that it should also be possible to create structs anonymously as
   they also can implement protocols.
   - Delegates are a bit tricky because they are usually retained weakly so
   the anonymous object would be deallocated immediately.
   - Also using "class: XYZ {}" doesn't allow creating named objects
like "class object
   EmptyObject {}".

When talking about singletons people tend to first think at a very large
scale and about abstraction, factories, testability and whatever.
It's the little things which capture my interest more, like NSNull for
example.

class object NSNull {}

Or maybe a JSON Null:

protocol JSONNode {}
struct JSON {
    struct object Null: JSONNode {}
    struct Bool { … } // not an object but a type

    // …
}

Now the interesting part about a singleton NSNull (or the JSON one) is that
it represents both, a type and an instance.

array.append(NSNull)

Note that we cannot use a class and call NSNull() as this would create a
new instance instead of returning the singleton instance.
We would have to make a silly workaround like NSNull.null or
NSNull.sharedInstance.

Examples for JSON.Null:

jsonArray.append(JSON.Null) // used as instance

if jsonNode is JSON.Null { // used as type
   // …
}

let expectedJsonTypes: [JSONNode.Type] = [JSON.Null, JSON.Bool, …]

if jsonNode is JSON.Null { // used as type
   // …
}
if jsonNode == JSON.Null { // used as instance (assuming Equatable
conformance)
   // …
}






On Sat, Dec 12, 2015 at 2:29 AM, Andrey Tarantsov via swift-evolution <
swift-evolution at swift.org> wrote:

> I think that anonymous classes got lost amongst all the singletonphobia
> here, and yet making an anonymous local delegate class is often helpful.
>
> Perhaps we don't need an additional keyword, though; something like this
> could work too:
>
> view.delegate = class: SomeDelegate {
>   ...
> }()
>
> or perhaps you want a slightly customized object:
>
> view = class: UITextField {
>   func canBecomeFirstResponder() -> Bool { return false }
> }()
>
> Of course, we could just use a named local class, like others have pointed
> out, but unless you really want to name that thing (and the name would
> often be stupid), that's a just workaround for a lack of anonymous classes.
>
> A.
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151212/2431477f/attachment.html>


More information about the swift-evolution mailing list