Why this is working? Swift (UnsafeMutablePointer<Optional>) - swift

protocol Property {}
protocol OptionalProtpery : Property {
static func codeNilInto(pointer: UnsafePointer<Int>)
}
extension Optional : OptionalProtpery {
static func codeNilInto(pointer: UnsafePointer<Int>) {
(UnsafeMutablePointer(pointer) as UnsafeMutablePointer<Optional>).memory = nil
}
}
I am interested in this statement UnsafeMutablePointer<"Optional">
Why we don't have an error for instance: "Optional generic type and requires arguments <...>". Since specific type (for instance UnsafeMutablePointer<"Optional"<"Int">>) is not specified right over here.

protocol Property {}
protocol OptionalProtpery : Property {
static func codeNilInto(pointer: UnsafePointer<Int>)
}
extension Optional : OptionalProtpery {
static func codeNilInto(pointer: UnsafePointer<Int>) {
(UnsafeMutablePointer(pointer) as UnsafeMutablePointer<Optional>).memory = nil
}
}
var i = 1
let p = withUnsafePointer(&i) { (p) -> UnsafePointer<Int> in
return p
}
print(p.memory) // 1
//Optional.codeNilInto(p) // error: generic parameter 'Wrapped' could not be inferred
// you have to specify generic parameter !!!
Optional<Int>.codeNilInto(p)
Optional<Double>.codeNilIntro(p)
// or what ever you want to express
so, because Optional is generic, you code is 'OK'. By the way, what do you expect your code does?

Related

Syntactic help: constraining functions to generic class

I have a structure that I simplified like this:
protocol Protocol {
associatedtype T
var common: T { get }
}
class Superclass<T>: Protocol {
let common: T
init(common: T) { self.common = common }
}
class IntClass<T>: Superclass<T> {
let int = 5
}
class StringClass<T>: Superclass<T> {
let string = "String"
}
class Example<P: Protocol> {
let object: P
init(object: P) { self.object = object }
func common() -> P.T { object.common }
func int() -> Int where P == IntClass<Any> { object.int }
func string() -> String where P == StringClass<Any> { object.string }
}
I would like to create objects of the generic class Example where some of them contain an object of the also generic IntClass while others have a generic StringClass object. Now I’d like to add accessors on Example for IntClass and StringClass specific properties (so I don’t have to access them directly). They would need to be constrained to the respective class. These would be int() and string() in my example.
My example doesn’t work like intended though:
let intExample = Example(object: IntClass(common: Double(1)))
// 👍 (= expected)
intExample.common() // Double 1
// 👍 (= expected)
intExample.string() // Instance method 'string()' requires the types 'IntClass<Float>' and 'StringClass<Any>' be equivalent
// 👎 (= not expected)
intExample.int() // Instance method 'int()' requires the types 'IntClass<Float>' and 'IntClass<Any>' be equivalent
I also tried:
func int() -> Int where P == IntClass<P.T> { object.int }
With these compiler complaints:
- Generic class 'Example' requires that 'P' conform to 'Protocol'
- Same-type constraint 'P' == 'IntClass<P.T>' is recursive
- Value of type 'P' has no member 'int'
And I tried:
func string<T>() -> String where P == StringClass<T> { object.string }
which, when using like intExample.string() results in Generic parameter 'T' could not be inferred (next to Instance method 'string()' requires the types 'IntClass<Double>' and 'StringClass<T>' be equivalent).
I don’t want string() to appear on an Example<IntClass> object in code completion.
Is there a syntax to accomplish what I want (anything with typealias?) or would I have to navigate around that problem?
Since the properties you are trying to access here doesn't depend on the type parameter T of IntClass or StringClass, you can write two non generic protocols HasInt and HasString:
protocol HasInt {
var int: Int { get }
}
protocol HasString {
var string: String { get }
}
extension IntClass: HasInt { }
extension StringClass: HasString { }
Then you can constrain to the protocols, and access int and string through the protocol instead:
func int() -> Int where P: HasInt { object.int }
func string() -> String where P: HasString { object.string }

Returning a nil from an optional generic extension

Here's something I'm playing with. The problem is that I have a container class that has a generic argument which defines the type returned from a closure. I want to add a function that is only available if they generic type is optional and have that function return a instance containing a nil.
Here's the code I'm currently playing with (which won't compile):
open class Result<T>: Resolvable {
private let valueFactory: () -> T
fileprivate init(valueFactory: #escaping () -> T) {
self.valueFactory = valueFactory
}
func resolve() -> T {
return valueFactory()
}
}
public protocol OptionalType {}
extension Optional: OptionalType {}
public extension Result where T: OptionalType {
public static var `nil`: Result<T> {
return Result<T> { nil } // error: expression type 'Result<T>' is ambiguous without more context
}
}
Which I'd like to use like this:
let x: Result<Int?> = .nil
XCTAssertNil(x.resolve())
Any idea how to make this work?
I don't think you can achieve this with a static property, however you can achieve it with a static function:
extension Result {
static func `nil`<U>() -> Result where T == U? {
return .init { nil }
}
}
let x: Result<Int?> = .nil()
Functions are way more powerful than properties when it comes to generics.
Update After some consideration, you can have the static property, you only need to add an associated type to OptionalType, so that you'd know what kind of optional to have for the generic argument:
protocol OptionalType {
associatedtype Wrapped
}
extension Optional: OptionalType { }
extension Result where T: OptionalType {
static var `nil`: Result<T.Wrapped?> {
return Result<T.Wrapped?> { nil }
}
}
let x: Result<Int?> = .nil
One small downside is that theoretically it enables any kind of type to add conformance to OptionalType.

Swift Generic Protocol Function Parameters

This seems like it should work to me. All I am trying to do is make the Rule protocol able to performRule on whatever struct adopts that Rule protocol and then return a boolean. However, with the way my code is currently I cannot access any properties on the performRule(:value) value parameter. I feel like I am missing an important concept or something is buggy. You should be able to copy the code below into a playground to see the issue for yourself.
import Foundation
protocol NumberCalculation {
var number : NSNumber { get set }
}
protocol Rule {
var invalidMessage : String { get set }
func performRule<T>(value: T) -> Bool
}
struct GreaterThanRule : Rule, NumberCalculation {
var invalidMessage: String
var number : NSNumber
init(valueMustBeGreaterThan value: NSNumber, withInvalidMessage message : String = "") {
number = value
invalidMessage = message
}
func performRule<NSNumber>(value: NSNumber) -> Bool {
number.decimalValue // works
value.decimalValue // doesn't work
return true
}
}
Saying <NSNumber> defines a new generic placeholder type in your performRule(value:) method, which, as you've named it NSNumber, will shadow Foundation's NSNumber class – meaning that the value: parameter is of type your generic placeholder, not Foundation's NSNumber.
If you want it so that types conforming to Rule can choose their own type for the parameter of the performRule(value:) method – then you want an associated type, not a generic placeholder.
protocol NumberCalculation {
var number : NSNumber { get set }
}
protocol Rule {
// define associated type that conforming types must satisfy
// by providing a type to replace it with
associatedtype Value
var invalidMessage : String { get set }
func performRule(value: Value) -> Bool
}
struct GreaterThanRule : Rule, NumberCalculation {
var invalidMessage: String
var number : NSNumber
init(valueMustBeGreaterThan value: NSNumber, withInvalidMessage message : String = "") {
number = value
invalidMessage = message
}
// satisfy associated type implicitly by annotating the type of the parameter
// as NSNumber – the compiler will infer that Value == NSNumber.
func performRule(value: NSNumber) -> Bool {
number.decimalValue // works
value.decimalValue // also works!
return true
}
}

Swift 2.0 protocol extensions - typealias

I am trying to have a extend a protocol in the following way but I am getting the error: Cannot convert return expression of type typable to typable.
I thought by saying typalias MyType : inside MyType will have to be an entity that conforms to inside
struct typeable<T> {
let value : String = "hello world"
}
protocol inside {
func __myFunction() -> typeable<inside>
}
protocol outside : inside {
typealias MyType : inside
func myFunction() -> typeable<MyType>
}
extension outside {
final func __myFunction() -> typeable<inside> {
return self.myFunction()
}
}
struct thing : outside {
typealias MyType = thing
func myFunction() -> typeable<thing> {
return typeable<thing>()
}
}
Your inside protocol:
protocol inside {
func __myFunction() -> typeable<inside>
}
... requires a function with a return type typeable<inside>, which is not the same as typeable<T> where T: inside. On the other hand, the default implementation of the conforming candidate function in the extension of outside returns a typeable<MyType> where MyType has not been up-casted to inside...
The following code, however, or some variant thereof, may express your intent (as far as I understand it) without tripping up the compiler:
struct Typeable<T> {
init(_: T) {}
}
extension Typeable : CustomStringConvertible {
var description: String { return "I'm a \(self.dynamicType)" }
}
protocol InsideType {
func asTypeableInside() -> Typeable<Self>
}
protocol OutsideType : InsideType {
func asTypeableOutside() -> Typeable<Self>
}
extension OutsideType {
func asTypeableInside() -> Typeable<Self> {
return asTypeableOutside()
}
}
struct Outside {}
extension Outside : OutsideType {
func asTypeableOutside() -> Typeable<Outside> {
return Typeable(self)
}
}
... with following properties:
let o = Outside()
let x = o.asTypeableOutside()
print( o ) // prints: Outside()
print( x ) // prints: I'm a Typeable<Outside>
o is InsideType // always true
x is Typeable<InsideType> // always false
Typeable(o) is Typeable<Outside> // always true
Typeable(o) is Typeable<OutsideType> // always false
Typeable(o) is Typeable<InsideType> // always false
... bearing in mind that:
5 is CustomStringConvertible // always true
Typeable(5) is Typeable<CustomStringConvertible> // always false
It doesn't appear that the typealias MyType : inside within the outside protocol is visible in the outside extension. I was able to get the extension to compile by putting the typealias MyType = inside (note the = rather than :), but that made the thing struct error on compilation.
It's difficult to figure out what you're actually trying to do, more context would be helpful to fully grasp the problem at hand.
In the definition __myFunction in the extension to outside, the uninstantiated type MyType can be of any type which inherits inside, which may be instantiated anywhere outside is implemented. So returning a typeable<inside> as being of typeable<MyType> simply proved to be type mismatch.
You, however, can avoid the error changing the definition a little bit.
struct typeable<T> {
let value : String = "hello world"
}
protocol inside {
typealias MyType
func __myFunction() -> typeable<MyType>
}
protocol outside : inside {
typealias MyType : inside
func myFunction() -> typeable<MyType>
}
extension outside {
final func __myFunction() -> typeable<MyType> {
return self.myFunction()
}
}
struct thing : outside {
typealias MyType = thing
func myFunction() -> typeable<thing> {
return typeable<thing>()
}
}

Swift protocol with constrained associated type error "Type is not convertible"

I have created 2 protocols with associated types. A type conforming to Reader should be able to produce an instance of a type conforming to Value.
The layer of complexity comes from a type conforming to Manager should be able to produce a concrete Reader instance which produces a specific type of Value (either Value1 or Value2).
With my concrete implementation of Manager1 I'd like it to always produce Reader1 which in turn produces instances of Value1.
Could someone explain why
"Reader1 is not convertible to ManagedReaderType?"
When the erroneous line is changed to (for now) return nil it all compiles just fine but now I can't instantiate either Reader1 or Reader2.
The following can be pasted into a Playground to see the error:
import Foundation
protocol Value {
var value: Int { get }
}
protocol Reader {
typealias ReaderValueType: Value
func value() -> ReaderValueType
}
protocol Manager {
typealias ManagerValueType: Value
func read<ManagerReaderType: Reader where ManagerReaderType.ReaderValueType == ManagerValueType>() -> ManagerReaderType?
}
struct Value1: Value {
let value: Int = 1
}
struct Value2: Value {
let value: Int = 2
}
struct Reader1: Reader {
func value() -> Value1 {
return Value1()
}
}
struct Reader2: Reader {
func value() -> Value2 {
return Value2()
}
}
class Manager1: Manager {
typealias ManagerValueType = Value1
let v = ManagerValueType()
func read<ManagerReaderType: Reader where ManagerReaderType.ReaderValueType == ManagerValueType>() -> ManagerReaderType? {
return Reader1()// Error: "Reader1 is not convertible to ManagedReaderType?" Try swapping to return nil which does compile.
}
}
let manager = Manager1()
let v = manager.v.value
let a: Reader1? = manager.read()
a.dynamicType
The error occurs because ManagerReaderType in the read function is only a generic placeholder for any type which conforms to Reader and its ReaderValueType is equal to the one of ManagerReaderType. So the actual type of ManagerReaderType is not determined by the function itself, instead the type of the variable which gets assigned declares the type:
let manager = Manager1()
let reader1: Reader1? = manager.read() // ManagerReaderType is of type Reader1
let reader2: Reader2? = manager.read() // ManagerReaderType is of type Reader2
if you return nil it can be converted to any optional type so it always works.
As an alternative you can return a specific type of type Reader:
protocol Manager {
// this is similar to the Generator of a SequenceType which has the Element type
// but it constraints the ManagerReaderType to one specific Reader
typealias ManagerReaderType: Reader
func read() -> ManagerReaderType?
}
class Manager1: Manager {
func read() -> Reader1? {
return Reader1()
}
}
This is the best approach with protocols due to the lack of "true" generics (the following isn't supported (yet)):
// this would perfectly match your requirements
protocol Reader<T: Value> {
fun value() -> T
}
protocol Manager<T: Value> {
func read() -> Reader<T>?
}
class Manager1: Manager<Value1> {
func read() -> Reader<Value1>? {
return Reader1()
}
}
So the best workaround would be to make Reader a generic class and Reader1 and Reader2 subclass a specific generic type of it:
class Reader<T: Value> {
func value() -> T {
// or provide a dummy value
fatalError("implement me")
}
}
// a small change in the function signature
protocol Manager {
typealias ManagerValueType: Value
func read() -> Reader<ManagerValueType>?
}
class Reader1: Reader<Value1> {
override func value() -> Value1 {
return Value1()
}
}
class Reader2: Reader<Value2> {
override func value() -> Value2 {
return Value2()
}
}
class Manager1: Manager {
typealias ManagerValueType = Value1
func read() -> Reader<ManagerValueType>? {
return Reader1()
}
}
let manager = Manager1()
// you have to cast it, otherwise it is of type Reader<Value1>
let a: Reader1? = manager.read() as! Reader1?
This implementation should solve you problem, but the Readers are now reference types and a copy function should be considered.