What Does <> (Angle Brackets) Do on Class Names in Swift

What does (angle brackets) do on class names in swift?

It makes the class generic. The Swift standard library doesn't have a lot of examples of generic classes, but it has some very well-known generic structs and enums:

public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer

public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible

public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible

Read more about generics under “Generics” in The Swift Programming Language.

Swift array syntax using angle brackets


Before I move forward, I just want to be sure and ask others if this is definitely the same and it doesn't matter which format you choose.

Yes, they mean the same thing and it doesn't matter which you use. [Int] is pure syntactic sugar for Array<Int>, no more no less.

What does enclosing a class in angle brackets mean in TypeScript?

That's called Type Assertion or casting.

These are the same:

let square = <Square>{};
let square = {} as Square;

Example:

interface Props {
x: number;
y: number;
name: string;
}

let a = {};
a.x = 3; // error: Property 'x' does not exist on type `{}`

So you can do:

let a = {} as Props;
a.x = 3;

Or:

let a = <Props> {};

Which will do the same

#import using angle brackets and quote marks

Objective-C has this in common with C/C++; the quoted form is for "local" includes of files (you need to specify the relative path from the current file, e.g. #include "headers/my_header.h"), while the angle-bracket form is for "global" includes -- those found somewhere on the include path passed to the compiler (e.g. #include <math.h>).

So to have your own headers use < > not " " you need to pass either the relative or the absolute path for your header directory to the compiler. See "How to add a global include path for Xcode" for info on how to do that in Xcode.

See this MSDN page for more info.

What is the meaning of left angle bracket hyphen ( -) in Swift?

Yes, it is defined in ObjectMapper, in IntegerOperators.swift, and perhaps other places I haven't checked.

https://github.com/tristanhimmelman/ObjectMapper/blob/master/Sources/IntegerOperators.swift

There are several operator definitions in that module for various argument type combinations. Example:

public func <- <T: UnsignedInteger>(left: inout T, right: Map) {
switch right.mappingType {
case .fromJSON where right.isKeyPresent:
let value: T = toUnsignedInteger(right.currentValue) ?? 0
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}

How to solve this parse and balance angle brackets problem? (Javascript)

To simplify things, rather than using a stack array, consider using just a single number: the number of open < tags so far. When a > is encountered, if there are no current open tags, add a < to the beginning of the string (while keeping the open tag count at 0). Then, at the end, add a number of >s matching the number of currently open tags:





const process = (str) => {

let openCount = 0;

let additionalLeadingOpenTags = 0;

for (const char of str) {

if (char === '>') {

if (openCount === 0) {

additionalLeadingOpenTags++;

} else {

openCount--;

}

} else {

openCount++;

}

}

return '<'.repeat(additionalLeadingOpenTags) + str + '>'.repeat(openCount);

};


console.log('Input 1: ><<><');


result = process('><<><');


console.log('Output 1: ' + result);

console.log('Expected Output 1: ' + '<><<><>>');


console.log('Input 2: <><<');


result = process('<><<');


console.log('Output 2: ' + result);


console.log('Expected Output 2: ' + '<><<>>');


console.log('Input 3: <><<<>');


result = process('<><<<>');


console.log('Output 3: ' + result);


console.log('Expected Output 3: ' + '<><<<>>>');


console.log('Input 4: <><<<><');


result = process('<><<<><');


console.log('Output 4: ' + result);


console.log('Expected Output 4: ' + '<><<<><>>>');


console.log('Input 5: ><<>');


result = process('><<>');


console.log('Output 5: ' + result);


console.log('Expected Output 5: ' + '<><<>>');


console.log('Input 6: ><<<');


result = process('><<<');


console.log('Output 6: ' + result);


console.log('Expected Output 6: ' + '<><<<>>>');

What are the angle brackets … in an Obj-C class interface for?

The angle brackets in a class interface definition indicates the protocols that your class is conforming to.

A protocol is almost like an interface in Java or C#, with the addition that methods in an Objective-C protocol can be optional.

Additionaly in Objective-C you can declare a variable, argument or instance variable to conform to several protocols as well. Example

NSObject<NSCoding, UITableViewDelegate> *myVariable;

In this case the class must be NSObject or a subclass (only NSProxy and its subclasses would fail), and it must also conform to both NSCoding and UITableViewDelegate protocols.

In Java or C# this would only be possible by actually declaring said class.

Difference between angle bracket and double quotes while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original
directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

Syntax explanation: square brackets in Swift

Ok, this is the meaning of

var treasures: [Treasure] = []
  • var: you are declaring a variable
  • treasures: the name of your variable
  • [Treasure]: the type of your variable, in this case the type is Array of Treasure, the compiler will allow you to insert only object of type Treasure in your Array
  • []: the actual object (Array) referenced by your variable, in this case an empty Array.

E.g. if you want the Array to hold 2 elements you can write

var treasures: [Treasure] = [Treasure(), Treasure()]

Hope this helps.

Update:
My example can also be written this way

var treasures = [Treasure(), Treasure()]

Infact thanks to the Type Inference the compiler can deduce the type of the variable treasures looking at the type of the assigned value.

How does Swift disambiguate Type Arguments in Expression Contexts?

Thanks to @Martin R, I found the relevant part of the compiler source code, which contains a comment that explains how it resolves the ambiguity.

swift/ParseExpr.cpp, line 1533:

///   The generic-args case is ambiguous with an expression involving '<'
/// and '>' operators. The operator expression is favored unless a generic
/// argument list can be successfully parsed, and the closing bracket is
/// followed by one of these tokens:
/// lparen_following rparen lsquare_following rsquare lbrace rbrace
/// period_following comma semicolon

Basically, the compiler attempts to parse a list of types and then checks the token after the closing angle bracket. If that token is

  • a closing parenthesis, bracket or brace,
  • an opening parenthesis, bracket or period without whitespace between itself and the closing angle bracket (>(, >[, but not > (, > [),
  • an opening brace or
  • a comma or semicolon

It parses the expression as a generic call, otherwise it parses it as one or more relational expressions.

As described in the book Annotated C#, the problem is solved in a similar way in C#.



Related Topics



Leave a reply



Submit