3. Language
Java/Android Swift/iOS
import com.package.name; import frameworkname
int counter; var counter: Int
final String TAG = “Class Name”; let TAG = “Swfit Name”
private private
- fileprivate
default internal
protected -
- public
public open
4. Objects
Java/Android Swift/iOS
class Foo extends Bar {} class Foo: Bar
interface Baz {} protocol Baz
class Bar implements Baz {} class Bar: Baz
Foo() init()
void doWork(String arg) {] func doWork(arg: String) -> Void
String doWork(String arg, int type) {] func doWork(arg: String, type: Int) -> String
Foo item = new Foo(); var item = Foo()
item.doWork(arg); item.doWork(arg)
item.doWork(arg, type); item.doWork(arg, type: test)
5. Collection Types
Java/Android Swift/iOS
int [] someInts = new Int[10]; var someInts = [Int]()
String [] shoppingList = {“Eggs”, “Milk”}; var shoppingList = [“Eggs”, “Milk”]
Map<String, String> airports = new
HashMap<>();
var airports = [String: String]()
Map<String, String> airports =
new HashMap<>() {{
put(“YYZ”: “Toronto Pearson”);
put(“DUB”: “Dublin”)
}};
var airports = [“YYZ”: “Toronto Pearson”,
“DUB”: “Dublin” ]
airports.put(“LHR”, “London”); airports[“LHR”] = “London”
6. Control Flow
Java/Android Swift/iOS
for (int i = 1; i <= 5; i++) {} for index in 1...5 {}
for (int i = 1; i < 5; i++) {} for index in 1..<5 {}
for (int number: someInts) {} for number in someInts {}
do-while repeat-while
switch (type) {
case a:
doSomething(); break;
case b:
case c:
doSomething(); break;
default:
Log.d(TAG, “default”);
}
switch type {
case a:
doSomeThing()
case b, c:
doSomeThing()
default:
print(“default”)
}
7. Access level diagram
Class A
Extension Class A
Class B: A
Extension Class B
Module A
Module B
private
Class A
Extension Class A
Class B: A
Extension Class B
public:
Only allow
Class B and
Extension B to
use the public
class.
Class A
Extension Class A
Class B: A
Extension Class B
fileprivate:
Class A
and Extension A
in the same file.
Class A
Extension Class A
Class B: A
Extension Class B
open
Class A
Extension Class A
Class B: A
Extension Class B
internal
(Default)
8. Optionals
● ? - Has a value or no value at all (nil)
var surveyAnswer: String?
// surveyAnswer is automatically set to nil
let possibleString: String? = "An optional string."
let forcedString: String = possibleString!
// requires an exclamation mark
● ! - Implicitly Unwrapped Optional
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString
// no need for an exclamation mark
9. Optional Binding
● Use optional binding to find out whether an optional contains a value,
var myString:String?
myString = "Hello, Swift!"
if let yourString = myString {
println("Your string has - (yourString)")
}else {
println("Your string does not have a value")
}
10. guard
● A guard statement, like an if statement, executes statements depending on
the Boolean value of an expression.
func greet(person: [String: String]) {
guard !person.isEmpty,
let name = person["name"] else {
return
}
print("Hello (name)!")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in (location).")
}
func greet(person: [String: String]) {
if !person.isEmpty {
if let name = person["name"] {
print("Hello (name)!")
if let location = person["location"] {
print("I hope the weather is nice in (location).")
} else {
print("I hope the weather is nice near you.")
}
}
}
}
11. Closures
● Closures in Swift are similar to that of self-contained functions organized
as blocks and called anywhere like C and Objective C languages.
● Syntax
{ (parameters) -> return type in
statements
}
12. Closures example
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backward(_ s1: String, _ s2: String) -> Bool {
return s1 > s2
}
var reversedNames = names.sorted(by: backward)
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
13. Closures example
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
})
14. Inferring Type From Context
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
15. Implicit Returns from Single-Expression Closures
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
16. Shorthand Argument Names
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversedNames = names.sorted(by: { $0 > $1 } )
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
17. Escaping Closures
● Closures in Swift are similar to that of self-contained functions organized
as blocks and called anywhere like C and Objective C languages.
func getAppStatus(completionHandler: @escaping (IMailItem) -> Void) {
var appStatus = getAppStatusFromServer()
completionHandler(appStatus)
}
18. Interfaces as Callbacks (JAVA)
public interface IMailReceiveCallback {
void onMailReceive(IMailItem mailItem);
}
// AppManager.class
public static void reqGetAppStatus(IMailReceiveCallback appStatusCallback) {
IMailItem mailItem = getAppStatusFromServer();
appStatusCallback.onMailReceive(mailItem);
}
// Call method with callback.
AppManager.reqGetAppStatus(this, new IMailReceiveCallback() {
@Override
public void onMailReceive(IMailItem mailItem) {
Log.d(TAG, "app connection status: " + mailItem.getStatus());
}
});
19. Escaping Closures example
// AppManager.class
public static func getAppStatus(completionHandler: @escaping (IMailItem) -> Void) {
var appStatus = getAppStatusFromServer()
completionHandler(appStatus)
}
// Call method with completionHandler.
let appStatus = AppManager.getAppStatus(completionHandler: { mailItem in
print(mailItem.status)
})
20. Next topics
● struct and class
● enum
● interface and protocol
● extension
● multi thread
21. Reference
● The Swift Programming Language (Swift 3.0.1)
● Completion Handlers in Swift
● 从Java/Android到Swift iOS开发