Transitioning to Swift - PDF eBook Free Download. Transitioning to Swift is a fast- paced page guide that will help you get up to speed quickly on. Contribute to AboutObjectsTraining/transitioning-to-swiftmarriott development by creating an Transitioning to maltmagecapski.ga · Initial commit, 4 months ago. C ft Sw ov er i s 1. Get up to speed on Swift quickly by leveraging 1 your knowledge of Objective-C Transitioning to Swift Scott Gardner maltmagecapski.gashub. com For.
|Language:||English, Spanish, Indonesian|
|Genre:||Children & Youth|
|Distribution:||Free* [*Registration needed]|
Available. Gardner. Transitioning to Swift. Get up to speed on Swift quickly by leveraging your knowledge of Objective-C. Transitioning to. Swift. Scott Gardner. transitioning to swift. Transitioning To Swift. Page 1. Page 2. transitioning to swift transitioning to swift pdf. Page 2. Page 3. transitioning to swift code compliance. Few middle-income countries have successfully transitioned into advanced economies in the .. swift transition to an advanced economy. The South Korean .
NSCopying and noreturn attributes are also available for use with properties and functions, respectively. Chapter 6 will cover noreturn and Chapter 7 will cover NSCopying. The objc declaration attribute can be used to mark an entity as being available to Objective-C source code within the same module—which is required for protocols containing optional requirements; Chapters 7 and 8 will examine these use cases. Beginning iPhone Development with Swift http: Such is not the case in Swift, where is used only as a prefix for certain declaration attributes, as mentioned in the previous section, Declaration Attribute.
Declaring Variables and Constants Asterisks are all but gone, save for their continued use in operators, multiline comments, and declaration attributes. Swift abstracts pointer management for reference types such that a variable or constant that refers to an instance of a reference type is not a direct pointer to an address in memory as in Objective-C, and you do not write an asterisk to indicate that a variable or constant is a reference type.
Semicolons are no longer required at the end of statements, except when including multiple statements on the same line, such as in a for loop.
Declaring Values Number values in Swift can optionally use underscores to increase readability of long numbers. Apple encourages using Int instead of UInt, even if a stored integer value is intended to be non-negative, unless you specifically require an unsigned integer type or an integer type of a specific size Int can store any value between -2,,, and 2,,, ; this aids in code consistency and interoperability.
Swift will infer a floating-point number as type Double unless explicitly declared as type Float: Tables and compare creating variables and constants in Objective-C and Swift. Recognizing that creating constants in Objective-C is far less common than in Swift, the intention is to show as close a match syntactically as possible between the two languages.
Declaring Variables and Constants 21 Table And a Swift String type is simply a sequence of those clusters. You can create characters by typing in the actual Unicode character as seen in the previous tables , or you can use the string interpolation syntax: All of these are written the same way in Swift as they are in Objective-C.
Table provides examples of writing numeric literals in Objective-C and Swift. Declaring Variables and Constants 23 Table In recent years, Apple has also boosted encouragement of using properties instead of instance variables. As a result, access control in Objective-C has seen minimal usage as compared with other languages. Swift, by contrast, offers comprehensive access control, taking a somewhat avante-garde approach. Declaring Variables and Constants Protocol Adoption A basic introduction to declaring protocol adoption is provided here.
Complete coverage of protocols can be found in Chapter 8. In Objective-C, to create a variable or constant and declare that it adopts one or more protocols, you would create the variable or constant as type id and enclose one or more protocols in a comma-separated list within angle brackets.
In Swift, you can declare that a variable or constant adopts a protocol in the same manner as declaring type. Table compares creating a stored value that is of a type that adopts a protocol in Objective-C and Swift. Although constants must be assigned a value when declared except properties, as previously noted , variables do not require value assignment during declaration.
How you go about doing this in Swift is different than in Objective-C, however. In Objective-C, a variable declared without assigning a value is nil actually a pointer to nil. In Swift, nil literally means no value. In order for a variable of any type to optionally be able to store a value or be nil, its type must be marked as an optional.
This is done by explicitly declaring the type followed with a? This is a syntactic shortcut for declaring the variable of type Optional followed by angle brackets enclosing the value type: Declaring Variables and Constants 25 The former question mark syntax is preferred for declaring an optional.
A variable declared as optional without assigning a value is nil. It can subsequently be assigned a value of its specified type or be set to nil again. A constant can also be declared as optional, although because a constant is immutable, this is of lesser practical value: To explicitly unwrap an optional, suffix it with an!
If you are certain that an optional will always have a value, you can implicitly unwrap the optional during declaration by suffixing the type with an! Declaring Variables and Constants Syntax Reference Figure summarizes the syntax for creating variables and constants in Swift. Italicized text indicates optional components.
Syntax for creating variables and constants in Swift Summary This chapter provided an overview of Swift value types and explained how to create variables and constants in Swift. Swift is designed to be a modern programming language that blends simplified syntax, powerful capabilities, and strong compiler support, to help you write more succinct and readable code that is also less prone to runtime errors. After reading this chapter and writing the example code in your Swift playground or REPL, you should be comfortable with how to declare, store, and print out values in Swift.
The side-by-side nature used to compare Objective-C and Swift code in this chapter will be used throughout the book. Chapter 3 Working with Strings and Collections Chapter 2 introduced the basic structure of Swift and explained the different types, mutability versus immutability, and notable syntax changes, among other things.
This chapter builds on that foundation of knowledge, focusing on creating and manipulating strings and collections of values. However, this does not mean that there is complete interchangability between String and NSString. For example, String methods such as toInt , computed properties such as endIndex, and global functions such as countElements will not work with an NSString instance.
Much as in Objective-C, strings in Swift can be created in a variety of ways, including as empty strings, literal strings, and using format strings. Remember that the mutability of a String value in Swift is determined by whether it is initialized as a variable var or constant let , versus by class selection in Objective-C NSMutableString and NSString.
Working with Strings and Collections As in Objective-C and mentioned in the last chapter, a String type in Swift is actually an ordered collection i. Therefore, countElements can be called, passing a String type, and it will return the count of Character values that make up the string: Chapter 8 will cover protocols in full. Remember from the last chapter, however, that the Character type represents a sequence of extended grapheme clusters that are combined to produce a single human-readable character.
Reading further into the extension that adopts the CollectionType protocol will disclose how, then, to get the length of a String value in terms of the count of individual clusters: Working with Strings and Collections 29 var startIndex: These are computed properties that return the position of the index before the first cluster, and position of the index after the last cluster, respectively computed properties will be further covered in Chapter 7: This is not always the case, however: Let's create a String from circledStar and compare the results of countElements and endIndex: It is therefore possible that two String values made up using different clusters are considered equal and countElements returns the same result; however, their endIndex and utf16Count properties will be different.
Working with Strings and Collections println string2.
String has several init methods that can be used to create strings from integer value types, as well as a variety of init methods that use format strings wherein the format string arguments can either be provided as a comma-separated list or in an array. String also has a toInt method that will attempt to convert a String value to an Int value. Because this attempt may fail, an optional Int? Remember to unwrap the optional before use. A Character value can be appended to a String value using the append method.
Note A character literal assigned to a variable or constant will be implicitly inferred to be of type String. Explicitly cast a character as type Character as necessary. Remember that NSString instances in Objective-C are passed by reference unless explicitly copied, whereas String values in Swift are always passed by copy.
Working with Strings and Collections 31 Table Working with Strings and Collections Table Am I alone? NSMakeRange 13, 10 if string4! How do isEqualToString: How do you like me now? Array and Dictionary.
Although not a formal collection type, Swift does add a new type for which there is no counterpart in Objective-C that can be used for grouping multiple values into a single compound value, called a tuple. Creating Tuples Tuples, although new to Objective-C developers transitioning to Swift, are by no means a new programming construct.
Tuples can be found in several other languages, including Python, Haskell, and C. Tuples in Swift are intended for temporarily grouping related values, and Apple advises to not use tuples to create complex data structures. Common uses include returning multiple values from a function see Chapter 6 for details and to test multiple values in a switch case statement covered in Chapter 5.
For data structures that are more complex or will persist beyond a temporary scope, use a class or structure instead covered in Chapter 7. Tuple values are ordered and can be composed of the same or differing types. To create a tuple, enclose a comma-separated list of values in parentheses: You can also explicitly state the type of a tuple, as in the following example, which adheres to good form by making the variable an optional, because we do not assign a value: Int, String?
Because tuples are ordered lists, you can access tuple elements at their numerical order index beginning with 0 using dot syntax: Working with Strings and Collections More succinctly, tuples can also be decomposed into separate stored values using another tuple: Table compares creating arrays in Objective-C and Swift.
Notice the lack of using the const keyword in Objective-C, as doing so does not make the array any more immutable. In the previous table, the Swift array type is inferred based on the type of the values stored in the array. Specifying an array is optional using?
Table compares creating mutable empty arrays in Objective-C and Swift. Because our focus is on transitioning to and learning Swift, Objective-C examples will typically be a single common use-case versus being exhaustive. It is possible to store different types in a Swift array; however, doing so may produce unexpected results with type inference. What should be mentioned, however, is that if you need an array that can hold multiple types, you can do so by explicitly declaring a variable array of type [AnyClass] or [Any], the former being an array capable of holding any reference type, the latter capable of holding any type whatsoever; AnyClass is a typealias for AnyObject: Working with Strings and Collections 37 Objective-C dictionaries can only store objects, and can use any object for the key as long as it conforms to the NSCopying protocol.
Swift dictionaries can store any type and use any type for the key as long as it conforms to the Hashable protocol protocols are covered in Chapter 8. Also, members of a new type of enumeration in Swift in which its members are not specifically assigned a value can be used as dictionary keys enumerations are covered in Chapter 7.
The literal syntax for creating a Swift dictionary uses square brackets just like arrays, and has the same key: Table compares creating dictionaries in Objective-C and Swift. Table compares creating mutable empty dictionaries in Objective-C and Swift. Although the Swift standard library does not enable you to declare a Dictionary type that uses different hashable key types and multiple value types that is, [Hashable: The next section will cover modifying tuples and collections.
It is important first to gain a solid understanding of how mutability is applied to Swift tuples, arrays, and dictionaries. Swift tuples and collections declared as variables can be reassigned to new tuples or collections, respectively, of the same type.
Arrays and dictionaries— but not tuples—declared as variables can have items added to and removed from them. Arrays and dictionaries declared as constants cannot be reassigned, nor can they have items added or removed. Mutability of the values within a tuple or collection is applied as follows. Value types passed into a tuple or collection are passed by copy, inheriting the mutability of the tuple or collection. So a variable or constant value type assigned to a variable tuple or passed in to a variable array is copied in as a mutable variable.
Table summarizes the mutability of tuples, arrays, and dictionaries in Objective-C and Swift. Working with Strings and Collections 39 Table Enumerating collections, due to the relationship of these use cases to controlling program flow, is deferred to Chapter 5. Working with Strings and Collections Working with Tuples A tuple cannot be sorted, nor can it have items added to or removed from it. A variable tuple can be modified, and its value type elements can also be modified.
Use the same dot syntax to change the value of a tuple element as you would to access it, but each value can only be changed to a new value of the same type. Value types passed into a variable tuple can be modified, whereas value types passed into a constant tuple cannot. This is regardless of whether the value type being passed in is itself declared as a variable or constant, because—remember—value types are always passed by copy: Working with Strings and Collections 41 Working with Arrays Table compares several ways to work with arrays in Objective-C and Swift, following highlights of the similarities and differences between the two.
Swift uses the same subscript syntax as Objective-C to access array items. NSArray instances have count, firstObject, and lastObject properties, and, similarly, Array values have count, first, and last computed properties.
When replacing a range of values, the replacement array does not need to be the same length as the range it is replacing. There are two kinds of range operators: Range operators will be mentioned again in the next chapter on operators and receive additional coverage in Chapter 5 for their use in program control flow statements.
To check if an array is empty in Objective-C, the count property can be checked to see if it is greater than 0; however, Swift includes the isEmpty computed property for this purpose. Finding items in an NSArray is made possible by a variety of indexOf Swift simplifies this task with the find method, which searches the array passed in for the value passed in, and returns an optional wrapping the value if found, or nil if not.
Closures are a powerful feature Swift with a variety of different usage syntax options. For completeness, examples of closure usage with arrays will be included in Table using the most compact version of syntax possible.
Working with Strings and Collections developers, it should quickly become the de facto standard. See Chapter 6 for elaborate coverage of closures and the variety of syntax options.
Arrays can be sorted in Objective-C using a comparator block, selector, function, or descriptor. Swift matches these methods with removeAtIndex and others. Table includes setup code at the top for use in the examples that follow. Working with Strings and Collections 43 Table NSMakeRange array[ NO]; array. Swift dictionaries have isEmpty and count computed properties just like arrays, the latter of which is also available in Objective-C as a property of NSDictionary and NSMutableDictionary instances.
Working with Strings and Collections 45 for details , or new arrays can be created from the collections using syntax that will be demonstrated in Table The collections returned for both the keys and values computed properties are ordered ascending by key, as is the order of key-value pairs when a Dictionary value is printed out. Swift uses the same subscript syntax as Objective-C to access dictionary items.
Values can be retrieved and added using subscript syntax in both Objective-C and Swift. Retrieving a value from a Swift dictionary is handled differently. Because a lookup may not find a value for the key provided, the returned value is an optional of the value if found, or nil if not.
Unlike in Objective-C, however, updateValue forKey: Although Objective-C does not allow it, a key-value pair can be removed from a Swift Dictionary type by using subscript syntax to set the value to nil for the key.
One, 2: Two, 3: The same optional declarations? Italicized text indicates optional components, which are omitted in successive examples of identical usage for each type.
Working with Strings and Collections 47 Figure Syntax for creating strings in Swift Figure Syntax for creating tuples in Swift Figure Syntax for creating arrays in Swift www. Working with Strings and Collections Figure Syntax for creating dictionaries in Swift Summary In this chapter you learned how to create and work with strings and collections in Swift, as compared with performing these tasks in Objective-C.
Although there are many similarities between the two languages, it is important to not only understand the syntactic differences but also to strive toward taking full advantage of the powerful new capabilities provided in Swift. Chapter 4 Performing Operations This chapter will focus on performing operations, including arithmetic, logical, bitwise, type checking, and type casting.
Operator precedence and associativity rules will also be reviewed. Basic Operators Swift includes the same basic operators as Objective-C, yet it adheres to a slightly different set of rules for operator precedence and associativity that are intended to be simpler and more predictable.
Precedence and associativity will be covered later in this chapter. The basic operators are implemented in Swift in the same manner as Objective-C, with a few exceptions and additions that will be mentioned next, followed by a summary of all basic operators with examples in Tables through Custom reference types do not automatically implement these equal to operators; see Chapter 7 for details.
These equal to operators are also not implemented for other types such as structures in either language. However, custom operators can be created in Swift, and existing operators can be overloaded.
Creating custom operators and overloading existing operators will be covered in Chapter 6. These operators automatically apply to custom reference types, too. Swift expands usage of the remainder operator to include floating-point numbers. In Objective-C, value overflow and underflow is automatic, which can result in unexpected behavior and sometimes hard-to-find bugs.
Note When using an overflow operator, the first operand is referenced to determine legality of assignment before the operation is performed, instead of the result of the whole operation.
Along similar lines, division by 0 or calculating modulo 0 in Objective-C will return 0. In Swift, either attempt will result in a compile-time error unless you use the equivalent overflow operator, in which case 0 will be returned just like in Objective-C.
Performing Operations 51 Swift adds a new nil coalescing operator?? This operator provides a shorthand syntax alternative to using a ternary conditional operator. Although the ternary conditional operator?: In Swift, it is necessary to explicitly check if a nonoptional variable does not equal nil!
There are two more new Swift operators: Because these operators are predominantly used in controlling program flow, they will be covered in the next chapter, focused entirely on that topic.
Unary operators operate on a single target, binary on two targets, and ternary on three targets. Tables through summarize the basic operators found in Objective-C and Swift. Performing Operations Table Performing Operations 53 Table The logical NOT operator! In Objective-C, you may have also been used to using the NOT operator to check that a nonboolean variable is not nil. It may therefore benefit performance to place more computationally expensive expressions to the right of simpler expressions.
Logical operators are evaluated left to right, so use parentheses to group expressions and specify order of evaluation. And, generally, the use of parentheses is encouraged whenever it will help improve readability. Performing Operations 55 Table Swift supports all of the bitwise operators available in Objective-C.
An in-depth discussion of performing bitwise operations is beyond the scope of this book; however, the examples in Table should be sufficient to match these operations between Objective-C and Swift. As in the Basic Operators section, these operators will be introduced narratively with mention of important points relative to their counterpart operators or operations in Objective-C, followed by a summary of examples in Table ; the if conditional syntax used will be covered in the next chapter.
Checking if an object is of a certain class type in Objective-C involves calling two NSObject methods: Casting an object to a subclass is accomplished by prepending the instance with the subclass name in parentheses, which subsequently allows treating that object as the casted subclass. Type checking and type casting are performed in Swift via the is and as operators, respectively. The is operator returns true if the stored value being checked is an instance of the specified type or a subclass in the case of class types , or false if not.
The as operator will return an instance of the casted type if successful. For class types, when a stored value being presented as of a specific class type is actually an instance of a subclass, the as operator will force downcast that instance to the subclass type. However, if the stored value is not actually an instance of the casted type or a subclass in the case of class types , the downcast will fail at runtime and a runtime error will be triggered.
Therefore, the as? The as? However, the compiler will flag an error and thus prevent writing code that attempts to explicitly cast to a type that the stored value is not an actual instance of or a subclass of in the case of class types. Casting a value does not change the value in any way. For class types, full access to the properties and methods of the downcasted class type will only be available for the scope of the cast.
The type checking and casting examples in Table include empty class, subclass, and structure definitions, and program control flow statements necessary to demonstrate these concepts. Control flow statements are covered in Chapter 5 classes and structures in Chapter 7, and subclasses in Chapter 9. ParentClass interface SomeOtherClass: String, end integer: Performing Operations 59 Table Not an instance of Subclass Not an instance of Subclass Performing Operations Operator Precedence and Associativity Precedence rules apply when an expression contains two or more binary operators and parentheses are not used to group and explicitly specify the order in which operations should be performed.
Associativity rules group these operations in a left-to-right or right-to-left fashion based on the operator type. A general best practice when dealing with a complex arithmetic expression is to always use parentheses; this not only helps to ensure intended precedence and associativity, but it also clearly conveys your intentions.
Table compares operator precedence and associativity rules in Objective-C and Swift. Performing Operations 61 Table Performing Operations Tip Due to the differences in precedence between Objective-C and Swift operators, be careful when migrating Objective-C code to Swift to ensure that arithmetic expressions perform the intended calculations.
Behind the scenes, Swift transforms a nonparenthesized expression made up of multiple operators from a flat list of operands and operators into a tree made up of parenthesized subexpressions based on operator precedence and associativity.
Figure presents this visually as a binary expression tree. Performing Operations 63 Understanding how Swift transforms flat expressions into trees is of lesser importance when parentheses are used to explicity group expressions.
Summary As demonstrated in this chapter, operators in Swift facilitate performing a wide variety of operations, including doing math, checking equality, changing types, and shifting bits. Although operator precedence will logically be applied to flat expressions, it is always better to use parentheses to control order of operator execution and improve code readability.
Chapter 5 Controlling Program Flow Although there can be a multitude of ways in which to control program flow in code, often the best approach balances succinctness and readability with performance. In this chapter, the similarities and differences of each control flow construct in Objective-C and Swift will be examined, and entirely new capabilities in Swift will be introduced.
Range Operators Objective-C includes NSRange, which is a struct representing the location and length index of a series of values. Although it can be used outright to iterate over a range of NSUIntegers from range.
Swift offers two range operators that enable expressing and iterating over a range of index values: Both operators include a start value, an end value, and a generator to return each incremental value from the start value to each incremental value up to and including the end value in the case of the closed range operator, and up to but not including the end value in the case of the half-open range operator.
Controlling Program Flow a closed operator with the same start and end values represents a range of one value the end value , and a half-closed operator with the same start and end values represents an empty range.
Range operators can express ranges between negative and positive integers, as long as the start value is less than or equal to the end value. Both the start and end values of a range can be retrieved and set, and a range can be checked to see if it is empty: The destination picker in Xcode Because ranges are of forward index integers, the start value must be less than the final value.
It is therefore necessary to convert a range to something else in order to represent the range in reverse. Controlling Program Flow Tip Taking the time to explore Swift in this manner can be a great way to gain deeper insight into Swift. Swift offers four such statements—continue, break, fallthrough, and return—all of which also exist in Objective-C except fallthrough.
Of these, only the fallthrough statement does not also exist in Objective-C. It is used exclusively with a switch case statement, and its usage will be covered in the next section Conditional Statements.
The return statement can only be used within a function or method, to include being used within a control flow statement within a function see the next chapter for additional coverage and examples of usage. Note In Swift, methods are simply functions that are associated with a type, such as a class. Chapter 6 provides full coverage of functions and methods. The continue and break transfer statements work exactly the same in Swift as they do in Objective-C. Controlling Program Flow 69 of code after the loop.
As explained in the Conditional section, switch case statements break by default and thus do not require explicit use of a break statement; however, they must be used for case statements that do not provide at least one executable statement.
When used in a loop statement, break will terminate execution of the loop altogether, and transfer program flow to the next line of code after the loop.
Table summarizes the behavior of all four control transfer statements, and examples of usage exist throughout the remaining sections of this chapter. Conditional Statements Conditional statements provide a programmatic fork in the road.
Objective-C and Swift both offer two conditional statements: However, their implementations and usage differ significantly. Differences between the if statement in Objective-C and Swift begin with the fact that use of parentheses around the conditional in Swift is optional and this syntactic noise is discouraged.
Controlling Program Flow not optional in Swift, even if the body of the if statement is only one line. Additionally, in Objective-C, the conditional statement resolves to a boolean false for a value of 0 or nil, and otherwise, it resolves to a boolean true. In Swift, a conditional statement must equate to true or false. Swift also provides a way to create a optional and test it all at once in a conditional, referred to as optional binding using the if let or if var syntax.
Both Objective-C and Swift include the else if and else clauses for use in an if conditional statement. In Objective-C, a switch statement can only test an integer value signed or unsigned , which is enclosed in parentheses.
In Swift, the parentheses are also optional; yet, more important, any type can be tested, such as a Float, a CGPoint, a tuple, or even a custom reference type.
Another significant difference is that case statements do not implicitly fall through in Swift. That is, a case statement in Swift must either include a statement, a break statement to explicitly state that the program flow should break out of the switch statement, or a fallthrough keyword to explicitly state that program flow should continue to the statement s inside the next case statement.
Note The behavior of fallthrough in a Swift switch case is the same as when omitting the break statement for a switch case in Objective-C. Program flow transfers directly to the statement inside of the next case statement, without actually evaluating that case statement condition. A switch statement in Swift must be exhaustive; every possible value must be matched by a case statement or the default catch-all case.
Table provides comparative examples of if and switch statements in Objective-C and Swift. Recognizing the sheer magnitude of possible use cases of a switch statement in Swift, only a representative sample is provided—further exploration in a playground would be a worthwhile and further eye-opening exercise. Controlling Program Flow 71 Table Great job! Your grade: Controlling Program Flow Table Controlling Program Flow 73 Table They work similarly in Objective-C and Swift, except that the parentheses enclosing the conditional statement are optional in Swift see Table For example, these two for loops do the same thing: When used with an array, for-in will return each sequential member of the array.
When used with a dictionary, for-in will decompose each key-value pair into a tuple of key, value. Keep in mind that the sort order is undefined—although, while that truly means the order will seem random in Objective-C, in Swift, both the keys and values properties appear to return the list sorted ascending by the key.
Swift also includes a global enumerate function. Its primary use is with arrays in a for-in statement, returning a tuple of index, value for each array element.
However, enumerate can also be used with a dictionary, returning a tuple of tupleIndex, key, value for each entry, should the need arise to enumerate a dictionary in this manner. Table includes a variety of iteration and enumeration examples in Objective-C and Swift. Three 3: Three" 1: Table compares these features between Objective-C and Swift, albeit using highly contrived examples.
Controlling Program Flow 77 Table Of these control flow constructs, the switch statement is greatly improved on in Swift to make it the preferred choice for conditional statements of more than a couple possible branches, and the new range operator and stride functions offer significantly streamlined approaches to iteration. Swift functions are named closures that operate similarly to Objective-C methods.
Closures can also be unnamed aka, anonymous , in which case they are referred to as closure expressions. Since function syntax is also used to overload existing operators and create new custom operators, both tasks will also be covered in this chapter. Creating Functions Swift functions: Tip Swift functions that are defined within a type are referred to as methods.
The syntax of Objective-C methods and Swift functions is similar. Table compares the basic syntax of an Objective-C method and Swift function. ParamType paramOneName paramTwo: ParamType, paramTwoName: Creating Functions 81 Table compared the syntax of Objective-C instance method to what could be a global Swift function, or an instance method defined within a class, structure, or enumeration type. The next chapter will delve into creating these types and their associated methods.
It is enough to mention now, however, that these types can also define type methods, equivalent to class methods in Objective-C. Table compares the basic syntax to define a class method in Objective-C and type method in Swift, this time also demonstrating that a Swift function that takes no parameters and returns no value simply includes an empty set of parentheses for the input and omits the return syntax altogether.
Tables and will then list several comparable examples. As in Objective-C methods, parameters in Swift fuctions are only available within the scope of the function, thus called local parameter names. Local parameter names are not used when calling a function; only the argument value s are passed. To improve readability, Swift functions can also define external parameter names for use when calling the function, resulting in a function signature that closely resembles the inline parameter name syntax of Objective-C methods.
If defined, external parameter names must be used when calling the function. An external name can be the same as or different than the local parameter name with which it is paired. Creating Functions Tip Prefixing a local parameter name with a hash symbol in a function definition is a shorthand syntax way to define an external parameter name that is the same as the local parameter name.
Note Swift methods i. This will be covered in full in the next chapter. Unlike Objective-C, in which parameters are by default passed by copy and mutable within the scope of the function, Swift function parameters are constants by default, thus immutable within the function. However, similar to mutability of items added to collections, the items in a collection, or properties of a reference type, when passed as a parameter in a function, are mutable to the extent of those individual items or properties—even though the parameter value itself is not mutable i.
Although parameters are by default constants in a Swift function, it is possible to have the function create a mutable copy of the parameter, by explicity declaring the parameter as a variable using the var prefix.
Known as variable parameters, these parameters are mutable i. It is also possible to allow a function to modify the original variable being passed in as a parameter, such that those changes persist after the function has ended.
Using inout parameters in Swift is akin to passing by reference in Objective-C, i. These mutability rules are logical, although they may be a little overwhelming at first.
Examples in Table and the summary of parameter mutability rules in Table should help to form a solid understanding. Creating Functions 83 Objective-C does not allow setting default values for parameters. One workaround is pass and check for nil or [NSNull null] et al. Swift offers built-in support for setting default parameter values, which should be placed after parameters without default values to ensure proper order when calling the method.
Unless explicitly defined, external parameter names are automatically created for parameters with default values. Objective-C enables defining a method that can take a variadic parameter, requiring a nil-terminated list to be passed for the variadic parameter, and processing the list using a handful of C functions.
Swift streamlines this process significantly. Both Objective-C and Swift utilize an ellipsis And just like an Objective-C method, a Swift function can have only one variadic parameter, which also must be placed last in the parameter list. Swift functions can return a value, just like an Objective-C method.
A Swift function can also return multiple values, using a tuple. Remember from Chapter 2 that optional values must be unwrapped before use, such as by using optional binding or force unwrapping. In Objective-C, a scalar value being passed as a parameter or returned as a value of a different scalar type will be implicitly converted to the parameter or return type. However, the conversion may not be successful or may produce unexpected results. In Swift, a parameter or return value type value must be of the type specified.
Therefore, a value type of differing type will need to be converted to the parameter or return type beforehand, either using an initializer of the specified parameter or return type, if available, or else manual conversion will be necessary if not a different design of the function made altogether.
When dealing with class types in either Objective-C or Swift, a subclass may be passed or returned as a parent class type. The opposite of course is not true, that is, a value of a parent class cannot be passed or returned for an expected sublass type of that parent class. However, if the value is believed to actually be an instance of the required subclass type for the parameter or return value, it must be explicitly casted as that subclass type beforehand in Swift, using the as or as?
Creating Functions covered in Chapter 9, and methods functions of a type , as used in the Swift Single return value subclass example in Table , will be further described in the next chapter. Int, equalsString string: Function types are also used to define function parameter types and return types, essentially working like a prototype to define a blueprint that the function parameter must implement see coverage of prototypes in Chapter 8: String, withSomeFunction someFunction: MediumStyle, localizedStringFromDate: NSDateF timeStyle: ShortStyle ormatterMediumStyle timeStyle: NSMake Range startIndex..
NSString func sayGreeting greeting: String, toPerson person: NSInteger n1 func addInteger n1: Int, toInteger n2: NSInteger integer func convertToFloat integer: String, toString string2: Creating Functions 93 As previously mentioned, Swift functions can take functions as parameters, nest other functions, and return functions. The following example does all three. Any, var andNumber number2: Any, withFormatter formatter: Any, int2: This will be covered in the section Blocks and Closure Expressions.
Creating Functions 95 Table Creating Functions Table Objective-C does not provide true support for currying, although clever implementations that achieve a similar effect can be found online. Swift supports currying outright, and offers a specific syntax for defining a curried function: As mentioned, one or more arguments can be initially bound and used in forthcoming calls to the single-parameter curried function: String, price: Double quantity: Swift functions can be overloaded.
The overall signature, including the parameters and return type, is evaluated for uniqueness by the compiler. Creating Functions func processInput input: Code-completion for overloaded function in Swift Overloading is not limited to functions.
String, integer: Int, string: Creating Functions 99 Custom Operators Swift facilitates creating entirely new operators, with only a few limitations. A custom operator can also be defined as a series of two or more dots such as Custom operators must first be declared at a global level using the operator keyword, preceded by the prefix, infix, or postfix modifier to indicate the operator fixity.
Subsequent to being declared, custom operators are defined using standard function definition syntax: CGPoint, right: Creating Functions Tip Overloading existing operators and creating new custom operators are powerful capabilities. It is generally advisable to carefully consider the obfuscation-to-benefit ratio before undertaking either action, especially for code that will be shared. Blocks and Closure Expressions Like Objective-C blocks, Swift closure expressions can be called inline, or stored and passed around to be executed at a later time.
Both blocks and closure expressions can capture state, and they each deal similarly with avoiding strong reference cycles a. Table compares the basic syntax of Objective-C blocks and Swift closure expressions. Table demonstrates an Objective-C block compared to a series of Swift closure expressions ranging from explicit to terse, with setup code at the top and the output common to all versions of the Swift examples at the bottom.
Notes on the Swift examples immediately follow the table. Creating Functions This function type uses generic types, which will be covered in Chapter Because these shorthand argument names can be used in lieu of declaring parameter names, the in keyword can also be omitted and the argument names used directly in the body of the expression.
Notice also that when the last parameter of a function is a closure expression, that expression can be moved outside of the parentheses. Additionally, if the function does not take any other parameters, the parentheses can be omitted, too: Self, rhs: In Objective-C, the two most prominent scenarios in which a retain cycle can occur—wherein two objects hold a strong reference to each other and thus neither can ever be released and deallocated—are with storyboard outlet properties in the view controller, and when calling self within a block.
Similarly, strong reference cycles can occur in Swift with outlet properties and between two reference types, such as two classes or a class and a closure expression.
Working with storyboards and outlet properties is beyond the scope of this book. However, the latter situation will be addressed in the next chapter, alongside class reference types. Creating Functions Declaration and Type Attributes In a similar manner as stored values, function declarations can utilize declaration attributes to provide additional information about the function.
See Chapter 2 for a list of available declaration attributes. Figure demonstrates using the availability declaration attribute with the deprecated and message attribute arguments to mark a function as deprecated and provide information about its replacement. Applying declaration attributes to a function in Swift Using the obsoleted attribute argument instead would generate a compiler error and prevent using the function, and also display a message if provided.
Function types can apply type attributes including autoclosure to implicitly enclose an expression in a closure, and noreturn to specify that a function does not return to its caller: Functions and closure expressions are most closely related to Objective-C methods and blocks, respectively, and thus comparative examples and approaches were provided throughout the chapter, along with tables summarizing syntax structures and mutability rules.
As such, it represents a milestone turning point in your transition to programming in Swift, not just in syntax, but approach. Having followed along, typing in the sample code in a playground, REPL, or project, you may start to find yourself forgetting to type semicolons back in your Objective-C code, or inadvertently expecting Objective-C to infer your value types for you.
Chapter 7 Constructing Classes, Structures, and Enumerations As alluded to in previous chapters, and revealed fully in this one, Swift breaks new ground with class types, and upgrades structures and enumerations to first-class status.
In fact, there is less to say about the differences than similarities between classes and structures in Swift, and enumerations are not far off the mark, either. This chapter will introduce each of these constructs, first at a high level and then followed by deeper analysis of major considerations such as initialization, definition of properties and methods, and selection guidelines. Naming Conventions Swift follows the same naming conventions as Objective-C with regard to naming classes, structures, enumerations, properties, and methods.
Classes, structures, and enumerations are all formal types, and thus their names should begin with a capital letter and use camel casing. Properties and methods are not types, so, in order to differentiate them from types, their names should begin with a lowercase letter and also use camel casing. From defining properties and methods to declaring protocols and calling on delegates, classes can satisfy a wide variety of needs. Objective-C is a superset of C and utilizes basic C structures as an alternative to classes.
C structures are lighter-weight, although they are limited to storing scalar values i. Table compares classes and structures in Objective-C and Swift. Attributes are aligned horizontally to aid in cross-referencing. Constructing Classes, Structures, and Enumerations Table All of these similarities, differences, and new capabilities will be covered in the forthcoming sections. Classes There are three standout differences between classes in Objective-C and Swift: Swift does not require creating separate interface and implementation files 2.
Swift custom classes are not reliant on inheriting from a base class 3. Access control in Swift is entirely different This chapter will cover the first two of these variances. Chapter 9 will deal with subclassing-specific topics, and Chapter 10 will analyze access control. Swift answered that question: Whereas class source files in Objective-C have a file extension of either. In the case of Swift playgrounds, a.
Constructing Classes, Structures, and Enumerations Deferring the broader topic of access control for now, it is sufficient to understand here that the external interface for each Swift class or structure is made available to all other code within the module.
Swift recognizes each build target in an Xcode project as a separate module, and modules can be imported. Table compares the basic syntax of a class definition in Objective-C and Swift, absent of details for properties and methods, which will be covered later in this chapter.
Optional components are italicized, and in order to keep these comparisons straightforward, accoutrements such as constants, macros, and extensions in Objective-C are omitted.
ParentClassName, ProtocolName, Although it is technically also optional in Objective-C, most every class in Objective-C is a subclass of NSObject, for at least one reason: Without that method, a class would have to implement its own memory allocation process and return an instance of the class to then be initialized.
Classes in Swift are self-efficient with regard to the whole instantiation, initialization, and deinitialization process, inclusive of memory allocation. Also notice that a class in Swift may adopt one or more protocols, and protocols should be listed after the parent class if there is one.
Constructing Classes, Structures, and Enumerations Structures C structures in Objective-C facilitate storing scalar values, aggregates, or other structures as its members, and are passed by copy.
Member values are normally retrieved and set using dot notation syntax, and although they can also be instantiated and referenced via structure pointers, this is less common in Objective-C programming where a class is typically used for anything but simple pass-by-copy data structures. Table compares the basic syntax of structure definitions in Objective-C and Swift; properties and methods in Swift, which are optional will be covered shortly. The most notable differences between Swift structures and classes are: Enumerations enable grouping related values together as a specific type of value.
An enumeration can be iterated over such as in a switch statement , and enumeration members can be passed as parameters to a function. Additionally, member names receive the benefit of code-completion, thus eliminating typo-related bugs that can be common when using raw strings. Enumerations are also commonly used with bitwise shift operators to combine multiple members into a single bitmask value, for example, for use in setting options in a method. Swift takes enumerations to a whole new level.
One of the biggest differences is that Swift enumerations do not automatically assign a default integer value; member values are, by default, fully-fledged values of the enumeration type. Table compares enumerations between Objective-C and Swift. Constructing Classes, Structures, and Enumerations Initialization As already noted, Objective-C uses C-based structures and enumerations that do not have formal initializers although initializer functions or factory methods could be created to vend initialized instances.
Objective-C classes, along with Swift classes, structures, and enumerations, all define or inherit initializers that prepare an instance for use. The process of instantiation—which includes allocating the memory for an instance and then initializing it—is similar in outcome but significantly different in implementation between the two languages.
Class Initialization Objective-C classes can define one or more initializers, typically with one designated initializer, that can optionally set default property values and perform other initialization tasks.
This is an oversimplification of an elaborate process that has evolved over many years Automatic Reference Counting, a. ARC, is one of the most profound improvements. You can also use the value of M in further computations.
Computers have hundreds or thousands of pigeonholes. The formal term for pigeonholes is variables. But this term is somewhat misleading since pigeonholes don't behave like "vari- 37 ables" in mathematics , source: Learning Objective-C 2.
With the exception of the client being allowed to send broadcast packets in this case. As such, go ahead and run the old UDP listener program in one window, and broadcaster in another Learn AppleScript: The read pdf lotos What if you don't want to connect to a remote host iOS 5. I don't agree with most of the criticisms that I've listed in this article — for the most part, I think the criticisms are either trivialities or they're philosophically and technically misguided.
But Mac programmers can't fight against an overwhelming trend towards totally abstracted memory models that's largely happening outside the borders of Mac programming. For example, a website may provide an API for web developers that allows them to access specific information from the site.
You can get the default charset via static method java. See how easy it is to follow this program where REMs are used liberally. There are many easy modifications to this program that will make it more interesting. She found why her program was not working. Telerik, based in Waltham, Mass. Objective-C was famously verbose, meaning it was easy to read.
You can almost always follow what's going on [in Objective-C] because the method names are so detailed. Whereas [in Swift] you'd have to have a little more familiarity with the language before you picked it up ref. So far we have played with graphics and numbers. But computers can also manipulate letters and sym- bols. Instead of handling them one at a time, as with the numerical values of variables, your computer handles a whole string of characters at a time online.