How to define optional protocol requirements in swift? - objective-c

As far as I know you need to annotate a function this way:
#objc MyProtocol{
optional func yourOptionalMethod()
}
But why is it needed the #objc annotation?

From Apple Documentation:
NOTE
Optional protocol requirements can only be specified if your protocol
is marked with the #objc attribute.
This attribute indicates that the protocol should be exposed to
Objective-C code and is described in Using Swift with Cocoa and
Objective-C. Even if you are not interoperating with Objective-C, you
need to mark your protocols with the #objc attribute if you want to
specify optional requirements.
Note also that #objc protocols can be adopted only by classes, and not
by structures or enumerations. If you mark your protocol as #objc in
order to specify optional requirements, you will only be able to apply
that protocol to class types.

Please check Apple Documentation:
Also,
Optional protocol requirements can only be specified if your protocol is >marked with the #objc attribute.
This attribute indicates that the protocol should be exposed to >Objective-C code and is described in Using Swift with Cocoa and >Objective-C. Even if you are not interoperating with Objective-C, you >need to mark your protocols with the #objc attribute if you want to >specify optional requirements.
Note also that #objc protocols can be adopted only by classes, and not >by structures or enumerations. If you mark your protocol as #objc in >order to specify optional requirements, you will only be able to apply >that protocol to class types.
Again, explained here in Swift Documentation:
/// The protocol to which all types implicitly conform
typealias Any = protocol
/// The protocol to which all class types implicitly conform.
///
/// When used as a concrete type, all known `#objc` `class` methods and
/// properties are available, as implicitly-unwrapped-optional methods
/// and properties respectively, on each instance of `AnyClass`. For
/// example:
///
/// .. parsed-literal:
///
/// class C {
/// #objc class var cValue: Int { return 42 }
/// }
///
/// // If x has an #objc cValue: Int, return its value.
/// // Otherwise, return nil.
/// func getCValue(x: AnyClass) -> Int? {
/// return **x.cValue**
/// }
///
/// See also: `AnyObject`
typealias AnyClass = AnyObject.Type
/// The protocol to which all classes implicitly conform.
///
/// When used as a concrete type, all known `#objc` methods and
/// properties are available, as implicitly-unwrapped-optional methods
/// and properties respectively, on each instance of `AnyObject`. For
/// example:
///
/// .. parsed-literal:
///
/// class C {
/// #objc func getCValue() -> Int { return 42 }
/// }
///
/// // If x has a method #objc getValue()->Int, call it and
/// // return the result. Otherwise, return nil.
/// func getCValue1(x: AnyObject) -> Int? {
/// if let f: ()->Int = **x.getCValue** {
/// return f()
/// }
/// return nil
/// }
///
/// // A more idiomatic implementation using "optional chaining"
/// func getCValue2(x: AnyObject) -> Int? {
/// return **x.getCValue?()**
/// }
///
/// // An implementation that assumes the required method is present
/// func getCValue3(x: AnyObject) -> **Int** {
/// return **x.getCValue()** // x.getCValue is implicitly unwrapped.
/// }
///
/// See also: `AnyClass`
#objc protocol AnyObject {
}

Related

Visitor Pattern VS Iterator Pattern: visiting across hierarchy class?

I'm studying Visitor Pattern advantages, and quoting Design Patterns:
But an iteratorcan't work across object structures with different
types of elements. Forexample, the Iterator interface defined on page
295 can access only objects of type Item:
template <class Item>
clas Iterator { // ... Item CurrentItem() const; };
This implies that all elements the iterator can visit have a common parentclass Item.
Visitor does not have this restriction...
class Visitor {
public:
// ...
void VisitMyType(MyType*);
void VisitYourType(YourType*);
};
MyType and YourType do not have to be related throughinheritance at
all.
I agree about this quote, but I can't figure out an example where the Visitor Pattern could explore a structure (like a List) where objects collected in it are not related by a super class.
In other words, can you show me an example where the features above is true please?
First, you should know what these patterns are for.
The Iterator Pattern is used to access an aggregate sequentially without exposing its underlying representation. So you could Hide a List or array or similar aggregates behind an Iterator.
Visitor Pattern is used to perform an action on a structure of elements without changing the implementation of the elements themselves.
So you use the patterns in two different situations and not as alternatives to each other.
In the Visitor Pattern you implement an Interface IAcceptor in each element you want to visit. So the Visitor Pattern doesn't rely on a superclass but on Interfaces
public interface IAcceptor
{
public void Accept(IVisitor visitor);
}
So if you have a List of objects you can iterate over it and visit the objects implementing IAcceptor
public VisitorExample()
{
MyVisitorImplementation visitor = new MyVisitorImplementation();
List<object> objects = GetList();
foreach(IAcceptor item in objects)
item.Accept(visitor);
}
public interface IVisitor
{
public void Visit(MyAcceptorImplementation item);
public void Visit(AnotherAcceptorImplementation item);
}
public class MyAcceptorImplementation : IAcceptor
{
//Some Code ...
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
To complete the code here is Visitor to write to Console if it visits my or another implementation of an acceptor.
public class MyVisitorImplementation : IVisitor
{
public void Visit(MyAcceptorImplementation item)
{
Console.WriteLine("Mine");
}
public void Visit(AnotherAcceptorImplementation item)
{
Console.WriteLine("Another");
}
}
For more useful examples and better explanation have a look at Visitor Pattern and Iterator Pattern
EDIT: Here an example using both, the visitor and Iterator. The iterator is just the logic how to move through your aggregate. It would make more sense with a hierarchical structure.
public VisitorExample2()
{
MyVisitorImplementation visitor = new MyVisitorImplementation();
List<object> myListToHide = GetList();
//Here you hide that the aggregate is a List<object>
ConcreteIterator i = new ConcreteIterator(myListToHide);
IAcceptor item = i.First();
while(item != null)
{
item.Accept(visitor);
item = i.Next();
}
//... do something with the result
}
There are two good examples I know of where visitor is clearly preferable to iterator.
The first is interacting with some unknown set of class members, in particular in C++. For example, here's a visitor that prints out all the members of other classes. Imagine you're the author of Printer and someone you're unacquainted with is the author of Heterogeneous3Tuple.
#include <iostream>
template<class ElemType1, class ElemType2, class ElemType3>
class Heterogeneous3Tuple
{
public:
Heterogeneous3Tuple(ElemType1 elem1, ElemType2 elem2, ElemType3 elem3)
: elem1_(std::move(elem1)), elem2_(std::move(elem2)), elem3_(std::move(elem3))
{}
template<class Visitor>
void accept(const Visitor& visitor)
{
visitor(elem1_);
visitor(elem2_);
visitor(elem3_);
}
private:
ElemType1 elem1_;
ElemType2 elem2_;
ElemType3 elem3_;
};
class Printer
{
public:
template<class VisitedElemType>
void operator()(const VisitedElemType& visitee) const
{
std::cout << visitee << std::endl;
}
private:
};
int main() {
Heterogeneous3Tuple<char, int, double> h3t('a', 0, 3.14);
Printer p;
h3t.accept(p);
}
a
0
3.14
coliru
There's no sensible way to get an iterator to work here. Without even knowing what types our Printer class might interact with this works so long as the visitor is accept()ed and the elements all interact in a similar way with operator << and a stream.
The other good example I know of shows up in abstract syntax tree manipulations. CPython and LLVM both use visitors. Using a visitor here prevents code that manipulates certain AST nodes from needing to know how to iterate over all the various AST nodes that might branch in complicated ways. The LLVM source code goes into more detail. Here's the highlight:
/// Instruction visitors are used when you want to perform different actions
/// for different kinds of instructions without having to use lots of casts
/// and a big switch statement (in your code, that is).
///
/// To define your own visitor, inherit from this class, specifying your
/// new type for the 'SubClass' template parameter, and "override" visitXXX
/// functions in your class. I say "override" because this class is defined
/// in terms of statically resolved overloading, not virtual functions.
///
/// For example, here is a visitor that counts the number of malloc
/// instructions processed:
///
/// /// Declare the class. Note that we derive from InstVisitor instantiated
/// /// with _our new subclasses_ type.
/// ///
/// struct CountAllocaVisitor : public InstVisitor<CountAllocaVisitor> {
/// unsigned Count;
/// CountAllocaVisitor() : Count(0) {}
///
/// void visitAllocaInst(AllocaInst &AI) { ++Count; }
/// };
///
/// And this class would be used like this:
/// CountAllocaVisitor CAV;
/// CAV.visit(function);
/// NumAllocas = CAV.Count;

doxygen - How to hide a class without hidding its members in subclasses?

I have a code (in C++, but for other languages solution of problem is probably similar):
namespace details {
struct C {
/// Documentation for common method.
void c();
};
};
/// Documentation for class A
struct A: public details:C {
/// Documentation for method a
void a();
};
/// Documentation for class B
struct B: public details:C {
/// Documentation for method b
void b();
};
And I want to hide class C (and whole details namespace) in documentation (it exists only to make A and B implementation shorter). But I need to have A and B in documentation, with c member (and all other members inherited from C) documented, like for source:
/// Documentation for class A
struct A {
/// Documentation for method a
void a();
/// Documentation for common method.
void c();
};
/// Documentation for class B
struct B {
/// Documentation for method b
void b();
/// Documentation for common method.
void c();
};
How to do this properly?

XMLSerialization with WCF Enum Attribute ignored

I am having problem with serializing object before send to the wire.
Basically I am expecting my object to be serialized as
<verb operation="and">Show</verb>
However its ignoring the attribute as
<verb>Show</verb>
Below is the client proxy code
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.2152")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.starstandards.org/webservices/2005/10/transport")]
public enum OperationEnumeratedType
{
/// <remarks/>
///
and,
/// <remarks/>
///
or,
/// <remarks/>
///
not,
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public OperationEnumeratedType operation
{
get
{
return this.operationField;
}
set
{
this.operationField = value;
}
}
and Below is How I am Creating this object.
verb = new CriteriaLogicStringType
{
operation = OperationEnumeratedType.and,
Value = "Show"
}
Does anyone knows how can I get the Operation Attribute to appear in serialized xml?
Thanks
You should decorate the members of the OperationEnumeratedType enumeration with the EnumMemberAttribute, like this:
[DataContract]
public enum OperationEnumeratedType
{
[EnumMember]
And,
[EnumMember]
Or,
[EnumMember]
Not
}
Related resources:
Enumeration Types in Data Contracts

Problem with DataContract and hierarchy on WCF

i have a problem with an object in my wcf project.
I have lets say this object:
[DataContract(Name="ClassA")]
public class Person{
//---attributes---
}
[DataContract(Name="ClassB")]
public class Men : Person{
//---attributes---
}
Where ClassB is child of ClassA on the other side.
Then i have a method that is post:
[OperationContract]
[WebInvoke(UriTemplate= "Person", ResponseFormat = WebMessageFormat.Json, Method= "POST")]
public string PostPerson(Person person) {
if(person is Men){
//code...
}
}
The thing is that i receive the person (in the other side, they sendme as a ClassB) but the person is Men returns false.. why?
You need to add the [ServiceKnownType(typeof(Men))] attribute to the PostPerson method.
As Ryan Gross mentions, you need Men to be a known type. Here's a similar question/answer here on SO. One option not mentioned in the linked article is the KnownType attribute. Here's an example of code I've used in the past. The prerequisite is that this class is the base class for all of your data contracts and all of your data contracts are in the same assembly:
/// <summary>
/// Base class for all data contracts.
/// </summary>
[DataContract(Name = "Base", Namespace = "your namespace")]
[KnownType("GetKnownTypes")]
public class BaseDC : IExtensibleDataObject
{
#region Constants and Fields
/// <summary>
/// Instance used to control access to the known types list.
/// </summary>
private static readonly object _knownTypesLock = new object();
/// <summary>
/// Classes derived from this class. Needed to ensure proper functioning of the WCF data
/// constract serializer.
/// </summary>
private static List<Type> _knownTypes;
#endregion
#region Properties
/// <summary>
/// Gets or sets an <c>ExtensionDataObject</c> that contains data that is not recognized as belonging to the
/// data contract.
/// </summary>
public ExtensionDataObject ExtensionData { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Enumerates the types in the assembly containing <c>BaseDC</c> that derive from <c>BaseDC</c>.
/// </summary>
/// <returns>List of <c>BaseDC</c>-derived types.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Not appropriate for a property.")]
public static IEnumerable<Type> GetKnownTypes()
{
lock (_knownTypesLock)
{
if (_knownTypes == null)
{
_knownTypes = new List<Type>();
Assembly contractsAssembly = Assembly.GetAssembly(typeof(BaseDC));
Type[] assemblyTypes = contractsAssembly.GetTypes();
foreach (Type assemblyType in assemblyTypes)
{
if (assemblyType.IsClass && !assemblyType.IsGenericType)
{
if (assemblyType.IsSubclassOf(typeof(BaseDC)))
{
_knownTypes.Add(assemblyType);
}
}
}
_knownTypes.Add(typeof(BaseDC));
}
return _knownTypes;
}
}
#endregion
}

Using NInject to bind a generic interface, with a default if a binding for the generic type is not set

Imagine I have the following classes and interfaces:
public interface IService<T> { }
public class DefaultService<T> : IService<T> { }
public class FooService : IService<Foo> { }
public class BarService : IService<Bar> { }
I would then like to be able to get instances from the Kernel like this:
Kernel.Get<IService<Foo>>(); // Should return FooService
Kernel.Get<IService<Bar>>(); // Should return BarService
Kernel.Get<IService<Dog>>(); // Should return DefaultService
Kernel.Get<IService<Cat>>(); // Should return DefaultService
Kernel.Get<IService<Giraffe>>(); // Should return DefaultService
Is it possible to setup bindings using NInject (possibly using the Conventions extension), so that I don't have to manually bind every single possible implementation of IService?
I've been working on something similar recently and came up with somewhat simpler solution of your problem (although a bit weaker).
What should suffice is to bind a generic implementation (DefaultService) to the generic interface, and concrete implementations (FooService, BarService) to the concrete interfaces. When you ask for a concrete instance of the interface, Ninject resolves whether you defined the concrete binding. If you did, it gives you the appropriate instance, otherwise it falls through to the generic binding. The following code should do the trick.
var kernel = new StandardKernel();
kernel.Bind(typeof(IService<>)).To(typeof(DefaultService<>));
kernel.Bind<IService<Foo>>().To<FooService>();
kernel.Bind<IService<Bar>>().To<BarService>();
EDIT:
The concept works throughout the whole Ninject, so you can use it along with Extensions.Conventions as well.
e.g. define the following:
public class Foo{}
public class Bar{}
public class Dog{}
public interface IService<T>{}
public class DefaultService<T> : IService<T>{}
public class FooService : IService<Foo>{}
public class BarService : IService<Bar>{}
use conventions to bind the services:
kernel.Bind(x => x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(IService<>))
.BindSingleInterface());
and create and check the appropriate services:
Assert.IsInstanceOf<BarService>(kernel.Get<IService<Bar>>());
Assert.IsInstanceOf<FooService>(kernel.Get<IService<Foo>>());
Assert.IsInstanceOf<DefaultService<Dog>>(kernel.Get<IService<Dog>>());
I took the liberty of refactoring the answer from #cbp, so that it works for the new IBindingGenerator signature in Ninject v3 conventions. It's pretty much replacing the Process() method signature with the CreateBindings() method signature, but I didn't test this, so there's a chance you'll have to tweak it a bit if you use it.
/// <summary>
/// Creates bindings on open generic types.
/// This is similar to the out-of-the-box
/// <see cref="GenericBindingGenerator" />,
/// but allows a default class to be
/// specified if no other bindings can be found.
/// See the test case for usages.
/// </summary>
public class GenericBindingGeneratorWithDefault : IBindingGenerator
{
private static readonly Type TypeOfObject = typeof(object);
private readonly Type _contractType;
private readonly Dictionary<Type, Type> _cachedBindings;
private readonly Type _defaultType;
public GenericBindingGeneratorWithDefault(Type contractType, Type defaultType)
{
if (!(contractType.IsGenericType || contractType.ContainsGenericParameters))
throw new ArgumentException("The contract must be an open generic type.",
"contractType");
_cachedBindings = new Dictionary<Type, Type>();
_contractType = contractType;
_defaultType = defaultType;
}
/// <summary>
/// Creates the bindings for a type.
/// </summary>
/// <param name="type">The type for which the bindings are created.</param>
/// <param name="bindingRoot">The binding root that is used to create the bindings.</param>
/// <returns>
/// The syntaxes for the created bindings to configure more options.
/// </returns>
public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
{
if (type == null) throw new ArgumentNullException("type");
if (bindingRoot == null) throw new ArgumentNullException("bindingRoot");
if (type.IsInterface || type.IsAbstract) yield break;
if (type == _defaultType)
{
yield return bindingRoot.Bind(_contractType).ToMethod(
ctx =>
{
Type requestedType = ctx.Request.Service;
Type resolution = _cachedBindings.ContainsKey(requestedType)
? _cachedBindings[requestedType]
: _defaultType.MakeGenericType(ctx.GenericArguments);
return ctx.Kernel.Get(resolution);
});
}
else
{
Type interfaceType = ResolveClosingInterface(type);
if (interfaceType != null)
{
yield return bindingRoot.Bind(type).To(_cachedBindings[interfaceType]);
}
}
}
/// <summary>
/// Resolves the closing interface.
/// </summary>
/// <param name="targetType">Type of the target.</param>
/// <returns></returns>
private Type ResolveClosingInterface(Type targetType)
{
if (targetType.IsInterface || targetType.IsAbstract) return null;
do
{
Type[] interfaces = targetType.GetInterfaces();
foreach (Type #interface in interfaces)
{
if (!#interface.IsGenericType) continue;
if (#interface.GetGenericTypeDefinition() == _contractType)
{
return #interface;
}
}
targetType = targetType.BaseType;
} while (targetType != TypeOfObject);
return null;
}
}
I figured out how to do this after a couple of hours messing around with NInject Convention's GenericBindingGenerator.
If anyone is interested I can post it.
Update:
/// <summary>
/// Creates bindings on open generic types.
/// This is similar to the out-of-the-box <see cref="GenericBindingGenerator" />, but allows a default class to be
/// specified if no other bindings can be found. See the test case for usages.
/// </summary>
public class GenericBindingGeneratorWithDefault : IBindingGenerator
{
private static readonly Type TYPE_OF_OBJECT = typeof (object);
private readonly Type _contractType;
private Dictionary<Type, Type> _cachedBindings = new Dictionary<Type, Type>();
private readonly Type _defaultType;
public GenericBindingGeneratorWithDefault(Type contractType, Type defaultType)
{
if ( !( contractType.IsGenericType || contractType.ContainsGenericParameters ) )
{
throw new ArgumentException( "The contract must be an open generic type.", "contractType" );
}
_contractType = contractType;
_defaultType = defaultType;
}
/// <summary>
/// Processes the specified type creating kernel bindings.
/// </summary>
/// <param name="type">The type to process.</param>
/// <param name="scopeCallback">the scope callback.</param>
/// <param name="kernel">The kernel to configure.</param>
public void Process( Type type, Func<IContext, object> scopeCallback, IKernel kernel )
{
if (type == _defaultType)
{
kernel.Bind(_contractType).ToMethod(
ctx =>
{
var requestedType = ctx.Request.Service;
var resolution = _cachedBindings.ContainsKey(requestedType)
? _cachedBindings[requestedType]
: _defaultType.MakeGenericType(ctx.GenericArguments);
return ctx.Kernel.Get(resolution);
});
}
else
{
Type interfaceType = ResolveClosingInterface(type);
if (interfaceType != null)
{
_cachedBindings[interfaceType] = type;
}
}
}
/// <summary>
/// Resolves the closing interface.
/// </summary>
/// <param name="targetType">Type of the target.</param>
/// <returns></returns>
public Type ResolveClosingInterface( Type targetType )
{
if ( targetType.IsInterface || targetType.IsAbstract )
{
return null;
}
do
{
Type[] interfaces = targetType.GetInterfaces();
foreach ( Type #interface in interfaces )
{
if ( !#interface.IsGenericType )
{
continue;
}
if ( #interface.GetGenericTypeDefinition() == _contractType )
{
return #interface;
}
}
targetType = targetType.BaseType;
} while ( targetType != TYPE_OF_OBJECT );
return null;
}
}