Anonymous class in swift - swift

Is there an equivalent syntax or technique for Anonymous class in Swift?
Just for clarification Anonymous class in Java example here - http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Thanks!

There is no equivalent syntax, as far as I know.
Regarding equivalent techniques, theoretically you could use closures and define structs and classes inside them. Sadly, I can't get this to work in a playground or project without making it crash. Most likely this isn't ready to be used in the current beta.
Something like...
protocol SomeProtocol {
func hello()
}
let closure : () -> () = {
class NotSoAnonymousClass : SomeProtocol {
func hello() {
println("Hello")
}
}
let object = NotSoAnonymousClass()
object.hello()
}
...currently outputs this error:
invalid linkage type for global declaration
%swift.full_heapmetadata* #_TMdCFIv4Test7closureFT_T_iU_FT_T_L_19NotSoAnonymousClass
LLVM ERROR: Broken module found, compilation aborted!
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 1

You can also create a basic empty class that acts like a bare protocol, and pass a closure to the init function that overrides anything you want, like this:
class EmptyClass {
var someFunc: () -> () = { }
init(overrides: EmptyClass -> EmptyClass) {
overrides(self)
}
}
// Now you initialize 'EmptyClass' with a closure that sets
// whatever variable properties you want to override:
let workingClass = EmptyClass { ec in
ec.someFunc = { println("It worked!") }
return ec
}
workingClass.someFunc() // Outputs: "It worked!"
It is not technically 'anonymous' but it works the same way. You are given an empty shell of a class, and then you fill it in or override whatever parameters you want when you initialize it with a closure.
It's basically the same, except instead of fulfilling the expectations of a protocol, it is overriding the properties of a class.

For example, Java listener/adapter pattern would be translated to Swift like this:
protocol EventListener {
func handleEvent(event: Int) -> ()
}
class Adapter : EventListener {
func handleEvent(event: Int) -> () {
}
}
var instance: EventListener = {
class NotSoAnonymous : Adapter {
override func handleEvent(event: Int) {
println("Event: \(event)")
}
}
return NotSoAnonymous()
}()
instance.handleEvent(10)
(Crashing the compiler on Beta 2)
The problem is, you always have to specify a name. I don't think Apple will ever introduce anonymous classes (and structs etc.) because it would be pretty difficult to come with a syntax that doesn't collide with the trailing closures.
Also in programming anonymous things are bad. Naming things help readers to understand the code.

No anonymous class syntax in Swift. But, you can create a class inside a class and class methods:
class ViewController: UIViewController {
class anonymousSwiftClass {
func add(number1:Int, number2:Int) -> Int {
return number1+number2;
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
class innerSwiftClass {
func sub(number1:Int, number2:Int) -> Int {
return number1-number2;
}
}
var inner = innerSwiftClass();
println(inner.sub(2, number2: 3));
var anonymous = anonymousSwiftClass();
println(anonymous.add(2, number2: 3));
}
}

This is what I ended up doing (Observer pattern). You can use closures in a similar way you would use anonymous classes in Java. With obvious limitations of course.
class Subject {
// array of closures
var observers: [() -> Void] = []
// #escaping says the closure will be called after the method returns
func register(observer: #escaping () -> Void) {
observers.append(observer)
}
func triggerEvent() {
observers.forEach { observer in
observer()
}
}
}
var subj = Subject()
// you can use a trailing closure
subj.register() {
print("observerd")
}
// or you can assign a closure to a variable so you can maybe use the reference to removeObserver() if you choose to implement that method
var namedObserver: () -> Void = {
print("named observer")
}
subj.register(observer: namedObserver)
subj.triggerEvent()
// output:
// observerd
// named observer

If you want to inline a click handler in Java style fashion, first define your closure as a variable in your button class:
var onButtonClick: () -> Void = {}
Then add a method to accept the closure as parameter and store it in the variable for later use:
func onClick(label: String, buttonClickHandler: #escaping () -> Void) {
button.label = label
onButtonClick = buttonClickHandler
}
Whenever the closure should be executed, call it in your button class:
onButtonClick()
And this is how to set the action that should occur on click:
newButton.onClick(label: "My button") { () in
print("button clicked")
}
You can also accept multiple parameters. For example, a toggle button may be handled like this:
var buttonClicked: (_ isOn: Bool) -> Void { set get }

Simply use a struct for defining the interface via function values and then anonymously implement it from a function, as is a very common way to write objects in JavaScript.
The function is only required for creating a private scope for the object returned.
import Foundation
struct Logger {
let info: (String) -> ()
let error: (String) -> ()
}
func createSimpleLogger() -> Logger {
var count = 0
func number() -> Int {
count += 1
return count
}
return Logger(
info: { message in
print("INFO - #\(number()) - \(message)")
},
error: { message in
print("ERROR - #\(number()) - \(message)")
}
)
}
let logger = createSimpleLogger()
logger.info("Example info log message")
logger.error("Example error log message")
Output:
INFO - #1 - Example info log message
ERROR - #2 - Example error log message

Related

Wrap a higher-order function in some context and apply it

Similar, I believe, to an applicative, I would like to wrap a higher-order function in some context and apply it to a sequence.
protocol Foo { func a() -> Void }
class Bar: Foo { func a() { } }
let seq = [Bar(), Bar(), Bar()]
Concretely, Give the above three definitions, I'd like to be able to call dispatch(event) where dispatch wraps up a forEach over a sequence of protocol instances, and event is a function defined by that protocol.
private func dispatch(event: () -> Void) -> Void {
DispatchQueue.main.async { // context that the forEach mapping should happen inside of
seq.forEach($0.event())
}
}
let _ = dispatch(Foo.a)
Obviously, this doesn't work with Swift's type system (I'm used to Clojure's apply()). As a possible alternative, is there a way to wrap the sequence into a partial that I can forEach on?
let dispatch() -> [Foo] {
DispatchQueue.main.async {
seq.forEach // 🤷🏻‍♂️
}
}
let _ = dispatch { $0.a() }
Perhaps dispatch should be thought of as a constrained extension to Sequence?
extension Sequence where Iterator.Element == Foo {
func dispatch() -> [Foo] {
DispatchQueue.main.async {
return self.forEach // 🤷🏾‍♀️
}
}
}
While not as elegant as could have been with key paths to instance methods, you could also create a dispatch function that takes in a closure with each element as its parameter:
func dispatch(_ handler: #escaping (Foo) -> Void) {
DispatchQueue.main.async {
seq.forEach(handler)
}
}
And invoke it like so:
dispatch { $0.a() }
While you can't use KeyPath for instance methods, you can use it for properties, if it works for you.
You can change your protocol and implementation to something like this:
protocol Foo {
var a: () -> Void { get }
}
class Bar: Foo {
lazy var a = {
print("Bar")
}
}
Then you can define your dispatch function to take a KeyPath as parameter:
extension Sequence where Iterator.Element: Foo {
func dispatch(keyPath: KeyPath<Foo, () -> Void>) {
DispatchQueue.main.async {
forEach { $0[keyPath: keyPath]() }
}
}
}
and pass the properties KeyPath as parameter:
let seq = [Bar(), Bar(), Bar()]
seq.dispatch(keyPath: \Foo.a)

Why Swift compiler cannot infer a type?

I've developed this generic method to execute requests:
func executeRequest<T, S, E>(_ request : RequestBuilder<T>,
map: (#escaping (T) -> S)) -> RepositoryResult<S, E> {
return RepositoryResult().doTask { result in
request.execute{ (response, error) in
// do some stuff
result.notifySuccess(value: map(body))
}
}
My map function is defined in a subclass with generic types:
class BaseMapper<R, U> {
class func transform(_ dataModel:R) -> U {
fatalError("Override this method")
}
// other generic methods
}
class HomeMapper:BaseMapper<HomeDTO, Home> {
override class func transform(_ dataModel: HomeDTO) -> Home {
return Home(customerFirstName: dataModel.customerFirstName,
balance: MoneyMapper.transform(dataModel.balance),
accounts: AccountSummaryMapper.listTransform(dataModel.summaries))
}
}
If I call the request executor method passing directly the map function like that:
func getHomeInfo() -> RepositoryResult<Home, HomeError> {
return executeRequest(HomeAPI.getMyHomeWithRequestBuilder(), map: HomeMapper.transform)
}
I believe Swift compiler is crashing because it returns several random errors: "Segmentation fault: 11". Otherwise, if I call the method specifying the "S" return type, it works:
func getHomeInfo() -> RepositoryResult<Home, HomeError>{
return executeRequest(HomeAPI.getMyHomeWithRequestBuilder(), map: { (homeDTO) -> Home in
HomeMapper.transform(homeDTO)
})
}
Furthermore, using a Mapper that doesn't inherit from BaseMapper and passing the function directly, it also works. Another thing that I don't understand is that RxSwift has a map function that works calling it with my first option...
Why swift compiler cannot infer "S" type? Why swift compiler is crashing and can't tell which line is crashing and why?
I've found a solution: associatedtypes
protocol Mappable {
associatedtype T
associatedtype S
static func transform(_ dataModel:T) -> S
}
class MapperHome : Mappable {
static func transform(_ dataModel: HomeDTO) -> Home {
return Home(customerFirstName: dataModel.customerFirstName,
balance: MoneyMapper.transform(dataModel.balance),
accounts: AccountSummaryMapper.listTransform(dataModel.summaries))
}
}
func getHomeInfo() -> RepositoryResult<Home, HomeError>{
return executeRequest(HomeAPI.getMyHomeWithRequestBuilder(), map: MapperHome.transform)
}
I don't understand why this code compiles and using inheritance instance of implementation of a protocol it doesn't... I don't know if it's a compiler bug or my fault.

Subclass Type as closure parameter

Usecase
I have a superclass (FirebaseObject) with subclasses for most data items in my Firebase (ex: RecipeItem, User). I made a function in the superclass that automatically updates the data that is in the subclass, now I am trying to make a function with closures that get called when the object is updated.
Code
class FirebaseObject {
private var closures: [((FirebaseObject) -> Void)] = []
public func didChange(completion: #escaping (((FirebaseObject) -> Void))) {
// Save closures for future updates to object
closures.append(completion)
// Activate closure with the current object
completion(self)
}
//...
}
This calls the closure with the initial object and saves it for later updates. In my Firebase observer I can now activate all the closures after the data is updated by calling:
self.closures.forEach { $0(self) }
To add these closures that listen for object changes I need to do:
let recipeObject = RecipeItem(data)
recipeObject.didChange { newFirebaseObject in
// Need to set Type even though recipeObject was already RecipeItem
// this will never fail
if let newRecipeObject = newFirebaseObject as? RecipeItem {
// Do something with newRecipeObject
}
}
Question
Is there a way to have the completion handler return the type of the subclass so I don't have to do as? Subclass even though it won't ever fail? I tried to do this with generic type but I can't figure it out and I am not sure if this is the correct solution.
I would like to keep most code in the FirebaseObject class so I don't need to add a lot of code when creating a new subclass.
Edit
Based on this article I tried to add the type when creating a subclass:
class RecipeItem: FirebaseObject<RecipeItem> {
//...
}
class FirebaseObject<ItemType> {
private var handlers: [((ItemType) -> Void)] = []
public func didChange(completion: #escaping (((ItemType) -> Void))) {
//...
This compiles but it crashes as soon as RecipeItem is initialised. I also tried
class RecipeItem: FirebaseObject<RecipeItem.Type> {
//...
}
But this gives an interesting compiler error when I try to access RecipeItem data in didChange closure:
Instance member 'title' cannot be used on type 'RecipeItem'
Ok, so I've been working on this for a day and I have found a way to do it using the method in this answer for the didChange and initObserver functions and taking inspiration from this way of saving data in extensions.
First off, all the functions that need to use the type of the subclass are moved to a protocol.
protocol FirebaseObjectType {}
extension FirebaseObjectType where Self: FirebaseObject {
private func initObserver(at ref: DatabaseReference) {
//...
}
mutating func didChange(completion: #escaping (((Self) -> Void))) {
if observer == nil {
// init Firebase observer here so there will be no Firebase
// observer running when you don't check for changes of the
// object, and so the Firebase call uses the type of whatever
// FirebaseObject this function is called on eg:
// RecipeItem.didChange returns RecipeItem
// and NOT:
// RecipeItem.didChange returns FirebaseObject
initObserver(at: ref)
}
if closureWrapper == nil {
// init closureWrapper here instead of in init() so it uses
// the class this function is called on instead of FirebaseObject
closureWrapper = ClosureWrapper<Self>()
}
// Save closure for future updates to object
closures.append(completion)
// Activate closure with current object
completion(self)
}
}
To save the closures I now use a wrapper class so I can do type checking on that. In FirebaseObject:
class ClosureWrapper<T> {
var array: [((T) -> Void)]
init() {
array = []
}
}
fileprivate var closureWrapper: AnyObject?
Now I can get the closures with the right type in FirebaseObjectType protocol:
private var closures: [((Self) -> Void)] {
get {
let closureWrapper = self.closureWrapper as? ClosureWrapper<Self>
return closureWrapper?.array ?? []
}
set {
if let closureWrapper = closureWrapper as? ClosureWrapper<Self> {
closureWrapper.array = newValue
}
}
}
I can now use didChange on a FirebaseObject subclass without checking its type every time.
var recipe = RecipeItem(data)
recipe.didChange { newRecipe in
// Do something with newRecipe
}

swift - Pass generic type to method with more specific extension requirements

So the title is a little weirdly worded, but here is the basis of what I am looking to do. I want to make a function that can determine if the generic type given extends from a specific protocol and then pass through the type to the more specific method for processing. This would be using the swift programming language to do so.
Psuedo code of what I want to achieve below:
func doStuff<T>(callback: Callback<T>) {
// Pseudo code of what I want to achieve as I'm not sure the syntax
// nor if it's even possible
if T extends Protocol {
let tExtendsProtocolType = T.Type as Protocol
mapStuffSpecific<tExtendsProtocolType>(callback: callback)
} else {
// Standard Use Case
}
}
func doStuffSpecific<T: Protocol>(callback: Callback<T> {
}
Thanks in advance
EDIT 1
typealias Callback<T> = (T) -> Void
protocol Protocol {}
struct A {}
struct B: Protocol {}
// I want to be able to use this to do some common set up then call into either doStuff<T> or doStuff<T: Protocol>
func tryDoStuff<T>(callback: Callback<T>) {
// Do some common setup then call this
doStuff(callback: callback)
}
func doStuff<T>(callback: Callback<T>) {
print("doStuff")
}
func doStuff<T: Protocol>(callback: Callback<T>) {
print("doStuffSpecific")
}
let callbackA: Callback<A> = { _ in } // Just an empty closure
let callbackB: Callback<B> = { _ in }
tryDoStuff(callback: callbackA) // prints doStuff
tryDoStuff(callback: callbackB) // prints doStuffSpecific
Swift's overload resolution algorithm already prioritizes the most specific overload available. Here's an example:
typealias Callback<T> = (T) -> Void
protocol Protocol {}
struct A {}
struct B: Protocol {}
func doStuff<T>(callback: Callback<T>) {
print("doStuff")
}
func doStuff<T: Protocol>(callback: Callback<T>) {
print("doStuffSpecific")
}
let callbackA: Callback<A> = { _ in } // Just an empty closure
let callbackB: Callback<B> = { _ in }
doStuff(callback: callbackA) // prints doStuff
doStuff(callback: callbackB) // prints doStuffSpecific

Create a Swift function with parameters that aren’t allowed to escape the function?

I have a function that is only valid to call within the context of another function, so I want swift stop consumers from capturing the inner function:
protocol Foo {
func bar(onlyValidToCallInsideBar: () -> Void)
}
class GoodFooImpl {
func bar(onlyValidToCallInsideBar: () -> Void) {
// do some stuff
onlyValidToCallInsideBar()
// do some more stuff
}
}
class CapturingBadFooImpl {
var badCaptureOfOnlyValidToCallInsideBar: (() -> Void)?
func bar(onlyValidToCallInsideBar: () -> Void) {
badCaptureOfOnlyValidToCallInsideBar = onlyValidToCallInsideBar
}
func fizz() {
badCaptureOfOnlyValidToCallInsideBar!()
}
}
class AsyncBadFooImpl {
func bar(onlyValidToCallInsideBar: () -> Void) {
dispatch_async(dispatch_get_main_queue()) {
onlyValidToCallInsideBar()
}
}
}
class FooConsumer {
func buzz(foo: Foo) {
bar() {
// This should only be called inside bar
}
}
}
I want to prevent impls like CapturingBadFooImpl and AsyncBadFooImpl.
Swift has nested functions. It sounds like you want to make your function nested inside another. Or, if you are creating a framework, you can make your function private. That prevents it from being used outside of its module (the framework).
If you don't mean one of those things you're going to have to explain what you want more clearly.