Skip to content

Instantly share code, notes, and snippets.

@below
Created November 8, 2016 13:48
Show Gist options
  • Select an option

  • Save below/3d8697bab362e477f6d13657bed6e6a3 to your computer and use it in GitHub Desktop.

Select an option

Save below/3d8697bab362e477f6d13657bed6e6a3 to your computer and use it in GitHub Desktop.
Why does this work if I test for the class, and not for the protocol?
//: Playground - noun: a place where people can play
import Foundation
protocol MyProtocol {
var value: Int! { get set }
}
class MyClass : MyProtocol {
var value : Int!
}
var foo : Any?
if let conformingProtocol = foo as? MyProtocol {
// Playground execution failed: error: MyPlayground.playground:17:30: error: cannot assign to property: 'conformingProtocol' is a 'let' constant
conformingProtocol.value = 5
// ~~~~~~~~~~~~~~~~~~ ^
}
if let conformingClass = foo as? MyClass {
conformingClass.value = 42
}
@below

below commented Nov 8, 2016

Copy link
Copy Markdown
Author

Solution is simple: The protocol could be implemented with a struct, and a struct property will not be mutable.

Therefore.

protocol MyProtocol : class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment