Assigning to a var defined in Protocol says that it can't assign to it - swift

Here is a simple use case:
protocol Debuggable {
var _d: String -> () {
get set
}
}
class Debugger {
class func attach(instance: Debuggable) {
let d = Debugger()
instance._d = d.d // This doesn't work
}
func d(message: String) {
println(message)
}
}
Error message at compile time: Cannot assign to _d in instance, although my protocol defines the var with a getter and setter.

This is a good case of the compiler catching an error for you :)
instance may be a value type and therefore be copied in to this method. In that case, you will modify the copy and just throw it out. The quickest fix is to define it as an inout parameter:
class func attach(inout instance: Debuggable) {
let d = Debugger()
instance._d = d.d
}
I think it would be better to return the instance though:
class func attach(instance: Debuggable) -> Debuggable {
let d = Debugger()
var ret = instance
ret._d = d.d
return ret
}
I feel that inout is mostly in the language for backwards compatibility to Objective-C and C. Let the type determine if it should be copied instead of forcing it to be passed by reference. If something is defined as a value type, there is a good reason for it.

Related

Variable of type Self in static context

I have to modify an existing static method with return type Self.
I am using Self as it is required to work for subclasses of A as well. As the modification potentially needs a dispatch sync block to create the data for the returnee, I have to introduce a local variable of type Self.
Error:
'Self' is only available in a protocol or as the result of a method in a class;
class A {
//...
}
class B:A {
//...
}
extension A {
static private func foo() -> Self {
var myVar: Self? //Error: 'Self' is only available in a protocol or as the result of a method in a class;
// Get data for myVar, potentially in a dispatch sync block on another queue
guard let safeVar = myVar else {
return someGarbagr
}
return myVar
}
}
Intended usage:
func someFunctionSomewhere() {
let instanceOfB = B.foo()
// use instanceOfB
}
I have tried all I can think of already:
type(of:Self)
Self.Type
...
I would like to avoid modifying it to a generic method for several reasons. The main reason is that we would have to mention the type explicitly to make a generic version be able to refer the return type:
let instanceOfB: B = B.foo()

Protocols and composition on Swift

I am trying to learn more about protocols and got stuck without understanding what is going on on the following piece of code. Mostly seeking some light and direction for good articles and pieces of explanation basically.
In one of the examples from Apple's Library protocols are doing a bit more than making sure the classes conform to it.
They are allowing objects from one class to access methods within other classes without using the traditional class inheritance definition.
This line of code let generator: RandomNumberGenerator on the Dice class is allowing the var d6 that is of type Dice to access a function func random() -> Double that is outside of Dice scope and inside LinearCongruentialGenerator scope and is using the RandomNumberGenerator to make this bridge.
Also allowing to do the following call d6.generator.random() when again .ramdom() is not on Dices scope.
protocol RandomNumberGenerator {
func random() -> Double
}
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c) % m)
return lastRandom/m
}
}
class Dice {
let sides: Int
let generator: RandomNumberGenerator
init(sides: Int, generator: RandomNumberGenerator) {
println(generator.random())
self.sides = sides
self.generator = generator
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) + 1
}
}
var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
Update to question
Thanks for the answers! By doing some research I think I just touched composition. So I wrote the code bellow to exemplify composition a bit better, without using protocols or delegates. Just pure composition. Please let me know if I got it right as it may help other people trying to understand composition.
class A {
var a1: String
init (valueToA: String){
self.a1 = valueToA
}
func aFunc1() -> A {
return self
}
}
class B {
var b1: A
init (valueToB: A ) {
self.b1 = valueToB
}
func bFunc1(){
println("I am bFunc and I am calling aFunc \(b1.aFunc1())")
}
}
var myA = A(valueToA: "Initiated myA with this string")
//myA.aFunc1()
var myB = B(valueToB: myA)
myB.b1 = A(valueToA: "a value to B")
myB.b1.aFunc1()
The same code but now with protocols
protocol myProtocol {
func protocolFunc(value: String) -> String
}
class A: myProtocol {
var a1: String
init (valueToA: String){
self.a1 = valueToA
}
func aFunc1() -> A {
return self
}
func protocolFunc(value: String) -> String {
return value
}
}
class B {
var b1: A
var b2: myProtocol
init (valueToB1: A, valueToB2: myProtocol ) {
self.b1 = valueToB1
self.b2 = valueToB2
}
func bFunc1(){
println("I am bFunc and I am calling aFunc \(b1.aFunc1())")
}
func callProtocolFuncOnA (value: String) {
b1.protocolFunc(value)
}
}
var myA1 = A(valueToA: "my A 1 created")
var myA2 = A(valueToA: "my A 2 created")
var myB = B(valueToB1: myA1, valueToB2: A(valueToA: "my A 3 created"))
myB.callProtocolFuncOnA("calling other function")
As #DevAndArtist says in his comment it allows encapsulation (abstraction) when a type of RandomNumberGenerator is passed in the initializer of the Dice class and so only that part of your implementation is visible to you.
In my humble opinion it could be better if the constant generator was not visible outside the Dice class scope as you say in your question, for example making his access modifier private, but remember that in your example all is set in the same swift file and this implies that the private access modifier isn't like the other programming languages like C#, Java, etc.
Even doing private you can access d6.generator.random() in your call because it exist in the same Swift file, the only way you can hide the property if you create a new Swift file for the Dice class and then this call when the property is private of course :
var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
println(d6.generator.random())
gave you the following error:
'Dice' does not have a member named 'generator'
And you can hide the property outside of its scope. It's only a point of view.
I hope this help you.

Using a Type Variable in a Generic

I have this question except for Swift. How do I use a Type variable in a generic?
I tried this:
func intType() -> Int.Type {
return Int.self
}
func test() {
var t = self.intType()
var arr = Array<t>() // Error: "'t' is not a type". Uh... yeah, it is.
}
This didn't work either:
var arr = Array<t.Type>() // Error: "'t' is not a type"
var arr = Array<t.self>() // Swift doesn't seem to even understand this syntax at all.
Is there a way to do this? I get the feeling that Swift just doesn't support it and is giving me somewhat ambiguous error messages.
Edit: Here's a more complex example where the problem can't be circumvented using a generic function header. Of course it doesn't make sense, but I have a sensible use for this kind of functionality somewhere in my code and would rather post a clean example instead of my actual code:
func someTypes() -> [Any.Type] {
var ret = [Any.Type]()
for (var i = 0; i<rand()%10; i++) {
if (rand()%2 == 0){ ret.append(Int.self) }
else {ret.append(String.self) }
}
return ret
}
func test() {
var ts = self.someTypes()
for t in ts {
var arr = Array<t>()
}
}
Swift's static typing means the type of a variable must be known at compile time.
In the context of a generic function func foo<T>() { ... }, T looks like a variable, but its type is actually known at compile time based on where the function is called from. The behavior of Array<T>() depends on T, but this information is known at compile time.
When using protocols, Swift employs dynamic dispatch, so you can write Array<MyProtocol>(), and the array simply stores references to things which implement MyProtocol — so when you get something out of the array, you have access to all functions/variables/typealiases required by MyProtocol.
But if t is actually a variable of kind Any.Type, Array<t>() is meaningless since its type is actually not known at compile time. (Since Array is a generic struct, the compiler needs know which type to use as the generic parameter, but this is not possible.)
I would recommend watching some videos from WWDC this year:
Protocol-Oriented Programming in Swift
Building Better Apps with Value Types in Swift
I found this slide particularly helpful for understanding protocols and dynamic dispatch:
There is a way and it's called generics. You could do something like that.
class func foo() {
test(Int.self)
}
class func test<T>(t: T.Type) {
var arr = Array<T>()
}
You will need to hint the compiler at the type you want to specialize the function with, one way or another. Another way is with return param (discarded in that case):
class func foo() {
let _:Int = test()
}
class func test<T>() -> T {
var arr = Array<T>()
}
And using generics on a class (or struct) you don't need the extra param:
class Whatever<T> {
var array = [T]() // another way to init the array.
}
let we = Whatever<Int>()
jtbandes' answer - that you can't use your current approach because Swift is statically typed - is correct.
However, if you're willing to create a whitelist of allowable types in your array, for example in an enum, you can dynamically initialize different types at runtime.
First, create an enum of allowable types:
enum Types {
case Int
case String
}
Create an Example class. Implement your someTypes() function to use these enum values. (You could easily transform a JSON array of strings into an array of this enum.)
class Example {
func someTypes() -> [Types] {
var ret = [Types]()
for _ in 1...rand()%10 {
if (rand()%2 == 0){ ret.append(.Int) }
else {ret.append(.String) }
}
return ret
}
Now implement your test function, using switch to scope arr for each allowable type:
func test() {
let types = self.someTypes()
for type in types {
switch type {
case .Int:
var arr = [Int]()
arr += [4]
case .String:
var arr = [String]()
arr += ["hi"]
}
}
}
}
As you may know, you could alternatively declare arr as [Any] to mix types (the "heterogenous" case in jtbandes' answer):
var arr = [Any]()
for type in types {
switch type {
case .Int:
arr += [4]
case .String:
arr += ["hi"]
}
}
print(arr)
I would break it down with the things you already learned from the first answer. I took the liberty to refactor some code. Here it is:
func someTypes<T>(t: T.Type) -> [Any.Type] {
var ret = [Any.Type]()
for _ in 0..<rand()%10 {
if (rand()%2 == 0){ ret.append(T.self) }
else {
ret.append(String.self)
}
}
return ret
}
func makeArray<T>(t: T) -> [T] {
return [T]()
}
func test() {
let ts = someTypes(Int.self)
for t in ts {
print(t)
}
}
This is somewhat working but I believe the way of doing this is very unorthodox. Could you use reflection (mirroring) instead?
Its possible so long as you can provide "a hint" to the compiler about the type of... T. So in the example below one must use : String?.
func cast<T>(_ value: Any) -> T? {
return value as? T
}
let inputValue: Any = "this is a test"
let casted: String? = cast(inputValue)
print(casted) // Optional("this is a test")
print(type(of: casted)) // Optional<String>
Why Swift doesn't just allow us to let casted = cast<String>(inputValue) I'll never know.
One annoying scenerio is when your func has no return value. Then its not always straightford to provide the necessary "hint". Lets look at this example...
func asyncCast<T>(_ value: Any, completion: (T?) -> Void) {
completion(value as? T)
}
The following client code DOES NOT COMPILE. It gives a "Generic parameter 'T' could not be inferred" error.
let inputValue: Any = "this is a test"
asyncCast(inputValue) { casted in
print(casted)
print(type(of: casted))
}
But you can solve this by providing a "hint" to compiler as follows:
asyncCast(inputValue) { (casted: String?) in
print(casted) // Optional("this is a test")
print(type(of: casted)) // Optional<String>
}

Swift generic parameter cannot be bound to non-#objc protocol

The following code produces a compile error of "Generic parameter "T" cannot be bound to non-#objc protocol type 'AAA' on the fail line. When I use a class instead of a protocol, it works ok. Also, if I add an #objc to the protocol it also works, but only in 6.4 beta. Any suggestions would be helpful.
protocol AAA {
var id: String { get set }
}
class BBB: AAA {
var id: String = ""
}
class BBBService {
func getAll<T:AAA>() -> [T] {
var returnArray:[T] = [T]()
return returnArray
}
}
class TestIt
{
func myTest() {
var service = BBBService()
var fail:[AAA] = service.getAll() // fails with Generic parameter "T" cannot be bound to non-#objc protocol type AAA
var succeed:[BBB] = service.getAll()
}
}
this also fails:
<T where T:AAA>
Update - from a practical perspective, adding the #objc causes other problems in my app. So, that is not an option at this point and time.
The trouble is with this line:
getAll<T: AAA>() -> [T]
you are declaring that T must be a concrete type that implements the protocol AAA. It’s important to distinguish between the protocol AAA, i.e. code like this:
func getAll() -> [AAA] {
var returnArray: [AAA] = [BBB()]
return returnArray
}
which works fine (returns an array of references to AAA-conforming objects, which could be of type BBB, or type CCC), and this:
func getAll<T: AAA>() -> [T] {
var returnArray: [T] = [] // what is T? No idea.
return returnArray
}
in which you are saying to the compiler “write me a version of getAll, in which T can be replaced by any specific type that implements AAA”.
This is why your second version compiles - you’re fixing T to be the actual type BBB.
Bear in mind, T might be a struct. In which case the array returned must be sized specifically for whatever struct is being held, right there as a value within the array. As opposed to if the protocol was #objc in which case it would at least be known to only be a class reference of a fixed size.
If what you actually want is an array of protocols, you should remove the generic placeholder and just return an array of protocols:
func getAll() -> [AAA] {
var returnArray: [AAA] = []
return returnArray
}

Cannot get protocol with typealias to work in Swift

Just trying to build a proof-of-concept lib in Swift with the following code:
import Foundation
protocol Resolver {
typealias ResolvedType
func get() -> ResolvedType
}
class FunctionResolver<T>: Resolver {
typealias ResolvedType = T
private var _resolver: () -> ResolvedType
init(resolver: () -> ResolvedType) {
_resolver = resolver
}
func get() -> ResolvedType {
return _resolver()
}
}
func singleton<T, U: Resolver where U.ResolvedType == T>(instance: T) -> U {
return FunctionResolver({ () -> T in instance }) as U
}
class TestObject {
init() { }
}
let obj = TestObject()
let r = singleton(obj)
However the last line fails with:
playground466.swift:30:9: error: cannot convert the expression's type 'TestObject' to type 'Resolver'
let r = singleton(obj)
^~~~~~~~~
Why is Swift trying to convert obj to a Resolver? I am not quite sure what I am missing there. I think this should work since all the type information is available inside the singleton method.
Am I introducing some kind of loops in the inferrencing system? How can I fix this so the last line works as intended (a resolver that resolves to same instance of obj)?
I am on the latest Xcode available on the dev portal.
EDIT: I tried simplifying it, still does not work:
func singleton<T: Resolver>(instance: T.ResolvedType) -> T {
return FunctionResolver(resolver: { () -> T.ResolvedType in instance }) as T
}
The problem is that in this function:
func singleton<T, U>(instance: T) -> U {
return FunctionResolver({ () -> T in instance }) as U
}
U cannot be inferred as an input parameter - instead it's the type of the variable you assign its return value used to infer the type. If you write:
let r = singleton(obj)
you are not providing enough info to determine what U is. So you should explicitly specify its type:
let r: FunctionResolver<TestObject> = singleton(obj)
I know... the error message doesn't help much :) As a general rule, if it doesn't make sense, the problem is elsewhere.
Looks like you're pushing the type inference system past it's limits.
singleton() function is parametrised with generic type and returns a value of that generic type. There is never any information about what type T actually is.
The easiest fix, since Swift doesn't support explicitly providing values for generics in function, is to determine the return type.
let obj = TestObject()
let r : FunctionResolver = singleton(obj)
Works properly.
But what if you doesn't want to specify the exact type, just that r is Resolver?
Tough luck. Swift doesn't support that. Protocols with associated types can be used only as a generic constrains, as the compiler error states.