SlideShare a Scribd company logo
From Android/Java to Swift (1)
Allan Shih
Agenda
● Brief language introduction
● Access control
● Optionals
● Closure
● Reference
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
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)
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”
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”)
}
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)
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
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")
}
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.")
}
}
}
}
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
}
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"]
Closures example
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
})
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"]
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"]
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"]
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)
}
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());
}
});
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)
})
Next topics
● struct and class
● enum
● interface and protocol
● extension
● multi thread
Reference
● The Swift Programming Language (Swift 3.0.1)
● Completion Handlers in Swift
● 从Java/Android到Swift iOS开发

More Related Content

PDF
Demystifying Shapeless
PDF
Scala jargon cheatsheet
PDF
Few simple-type-tricks in scala
PDF
Scala Types of Types @ Lambda Days
PDF
Swift in SwiftUI
PDF
High Wizardry in the Land of Scala
PDF
Scala cheatsheet
PDF
Quick swift tour
Demystifying Shapeless
Scala jargon cheatsheet
Few simple-type-tricks in scala
Scala Types of Types @ Lambda Days
Swift in SwiftUI
High Wizardry in the Land of Scala
Scala cheatsheet
Quick swift tour

What's hot (20)

PDF
From android/java to swift (3)
PDF
Swift Basics
PDF
42.type: Literal-based Singleton types
PPTX
Regular expressions
PPTX
Regular expressions
PDF
SE 20016 - programming languages landscape.
PPT
Intermediate JavaScript
PDF
Introduction to Swift 2
ODP
Scala Demystifying the Funky Stuff
PPT
Scala for Java Developers
PDF
Scala: A brief tutorial
PPTX
Introduction to Regular Expressions
PPTX
Practically Functional
PPT
The ruby programming language
PDF
Introduction To Scala
PPTX
Types by Adform Research, Saulius Valatka
PPTX
Scala fundamentals
PDF
A quick python_tour
PPTX
Scala syntax analysis
PDF
Ruby — An introduction
From android/java to swift (3)
Swift Basics
42.type: Literal-based Singleton types
Regular expressions
Regular expressions
SE 20016 - programming languages landscape.
Intermediate JavaScript
Introduction to Swift 2
Scala Demystifying the Funky Stuff
Scala for Java Developers
Scala: A brief tutorial
Introduction to Regular Expressions
Practically Functional
The ruby programming language
Introduction To Scala
Types by Adform Research, Saulius Valatka
Scala fundamentals
A quick python_tour
Scala syntax analysis
Ruby — An introduction
Ad

Similar to From android/java to swift (1) (20)

PDF
Intro toswift1
PDF
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
PDF
Developing Swift - Moving towards the future
PDF
Objective-C to Swift - Swift Cloud Workshop 3
PDF
Swift, swiftly
PPTX
A Few Interesting Things in Apple's Swift Programming Language
PDF
Swift rocks! #1
PDF
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
PDF
The swift programming language
PPT
Developing iOS apps with Swift
PDF
SV-ios-objc-to-swift
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02)
PDF
Welcome to Swift (CocoaCoder 6/12/14)
PDF
Advanced Swift Updated For Swift 5 Chris Eidhof
PDF
Swift Study #3
PDF
iOS for Android Developers (with Swift)
PDF
Workshop Swift
PDF
To Swift 2...and Beyond!
PDF
Hamamatsu.swift @浜松IT合同勉強会
Intro toswift1
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Developing Swift - Moving towards the future
Objective-C to Swift - Swift Cloud Workshop 3
Swift, swiftly
A Few Interesting Things in Apple's Swift Programming Language
Swift rocks! #1
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
The swift programming language
Developing iOS apps with Swift
SV-ios-objc-to-swift
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02)
Welcome to Swift (CocoaCoder 6/12/14)
Advanced Swift Updated For Swift 5 Chris Eidhof
Swift Study #3
iOS for Android Developers (with Swift)
Workshop Swift
To Swift 2...and Beyond!
Hamamatsu.swift @浜松IT合同勉強会
Ad

More from allanh0526 (17)

PPTX
PPTX
Digital authentication
PDF
Integration of slather and jenkins
PDF
How to generate code coverage reports in xcode with slather
PDF
Unit testing in xcode 8 with swift
PDF
Ui testing in xcode
PDF
How to work with dates and times in swift 3
PDF
Using a model view-view model architecture for iOS apps
PDF
iOS architecture patterns
PDF
ThingMaker in Swift
PDF
Automatic reference counting in Swift
PDF
Core data in Swfit
PDF
From android/ java to swift (2)
PDF
WebRTC
PDF
Pipeline interface
PDF
Deploying artifacts to archiva
PPT
Android httpclient
Digital authentication
Integration of slather and jenkins
How to generate code coverage reports in xcode with slather
Unit testing in xcode 8 with swift
Ui testing in xcode
How to work with dates and times in swift 3
Using a model view-view model architecture for iOS apps
iOS architecture patterns
ThingMaker in Swift
Automatic reference counting in Swift
Core data in Swfit
From android/ java to swift (2)
WebRTC
Pipeline interface
Deploying artifacts to archiva
Android httpclient

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced IT Governance
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Approach and Philosophy of On baking technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Empathic Computing: Creating Shared Understanding
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Network Security Unit 5.pdf for BCA BBA.
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced IT Governance
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
NewMind AI Weekly Chronicles - August'25 Week I
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Advanced methodologies resolving dimensionality complications for autism neur...
Approach and Philosophy of On baking technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Monthly Chronicles - July 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

From android/java to swift (1)

  • 1. From Android/Java to Swift (1) Allan Shih
  • 2. Agenda ● Brief language introduction ● Access control ● Optionals ● Closure ● Reference
  • 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开发