|
While learning Swift, while writing notes, we believe that under certain circumstances based on other languages 1.5 hours to master reading the article. Then spend 30 minutes to open the XCode write a Demo. Life took two hours to understand a language, it is worth it!
Notes divided into two parts, a basic knowledge of Swift, the second use Xcode to develop a software
[TOC]
swift Basics
Variables and constants
// Define the variable
var myVariable = 123
// Define constants
let myConstantVariable = 123
// Implicitly specified integer type
var anInteger = 2
// Explicitly specify the integer type
let anExplicitInteger: Int = 2
Tuple
let aTuple = (1, "Yes")
let anotherTuple = (aNumber: 1, aString: "Yes")
let theOtherNumber = anotherTuple.aNumber // = 1
Other Uses
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
print ( "The status code is (statusCode)")
More user function return values, the return value of more than two, like with golang
Array
var arrayOfIntegers: [Int] = [1,2,3]
// Implicitly designated
var implicitArrayOfIntegers = [1,2,3]
// You can also create an empty array, but must provide their type
let anotherArray = [Int] ()
// Function using the append append to the end of the array of objects
myArray.append (4)
Anywhere in the array // insert objects
myArray.insert (5, atIndex: 0)
dictionary
A dictionary is an array type that maps keys to values similar to Java's Map, PHP's
var crew = [
"Caption": "Jean-Luc Picard",
"First officer": "William Riker",
"Second Officer": "Data"
];
crew [ "Captain"]
// = "Jean-Luc Picard"
Control flow
if
if 1 + 1 == 2 {
println ( "The math checks out")
}
for-in
let loopingArray = [1,2,3,4,5]
var loopSum = 0
for number in loopingArray {
loopSum + = number
}
loopSum // = 15
var firstCounter = 0
for index in 1 .. <10 {
firstCounter ++
}
// Loop 9
var secondCounter = 0
for index in 1 ... 10 {// note the three dots, not two
secondCounter ++
}
// 10 cycles
var sum = 0
for var i = 0; i <3; i ++ {
sum + = 1
}
sum // = 3
while
var countDown = 5
while countDown> 0 {
countDown--
}
countDown // = 0
var countUP = 0
do {
countUp ++
} While countUp <5
countUp // = 5
if-let
You can use if-let statement checks whether the variable contains an optional value. If included, the specified value to a constant variable, and then run a section of code. This can reduce many lines of code, but also to ensure safety
var conditionalString:? String = "a string"
if let theString = conditionalString? {
println ( "The string is ' (theString)'")
} Else {
println ( "The string is nil")
}
// Prints "The string is 'a string'"
function
Single simple function return value
Two parameters, a return value, both for the Int
func thirdFunction (firstValue: Int, secondValue: Int) -> Int {
return firstValue + secondValue
}
thirdFunction (1, 2)
Multi-tuple return value
func fourthFunction (firstValue: Int, secondValue: Int)
-> (Doubled: Int, quadrupled: Int) {
return (firstValue * 2, secondValue * 4)
}
fourthFunction (2, 4)
// Use Digital Access:
fourthFunction (2, 4) .1 // = 16
// Otherwise identical, except that the name:
fourthFunction (2, 4) .quadrupled // = 16
External Name calling
When you define a function, you can specify the name as a parameter. When I could not understand the purpose of each parameter immediately, this feature will be very useful. It can be used to define the parameter names as follows:
func addNumbers (firstNumber num1: Int, toSecondNumber num2: Int) -> Int {
return num1 + num2
}
addNumbers (firstNumber: 2, toSecondNumber: 3) // = 5
When you create a name for the parameter name is to create an internal and an external parameter name, the name of an internal and external parameters should be the same name. Will enter the same name twice no problem, but it does have an easy way to define the internal name of an external parameter name the same - that is, before the parameter name put a # symbol
func multiplyNumbers (#firstNumber: Int, #multiplier: Int) -> Int {
return firstNumber * multiplier
}
multiplyNumbers (firstNumber: 2, multiplier: 3) // = 6
Function as a variable
var numbersFunc: (Int, Int) -> Int;
// NumbersFunc can now store accepts any two Int and returns an Int function
numbersFunc = addNumbers
numbersFunc (2, 3) // = 5
Closure closure
sort we need to pass a closure as a parameter
var numbers = [2,4,34,6,33,1,67,20]
var numbersSorted = numbers.sort ({(first, second) -> Bool in
return first
})
Closures contain only one line of code, you can omit the return keyword
var numbersSorted = numbers.sort ({$ 1> $ 0})
print (numbersSorted)
If a closure is a function call in the last parameter, which can be placed outside the brackets. This is purely to improve readability, the closure does not change the way of working
var numbersSorted = numbers.sort () {$ 1> $ 0}
print (numbersSorted)
Closure on the variables inside
var comparator = {(a: Int, b: Int) in a
comparator (1, 2) // = true
Objects
definition
class Vehicle {
var color: String?
var maxSpeed = 80
func description () -> String {
return "A (self.color) vehicle"
}
func travel () {
print ( "Traveling at (maxSpeed) kph")
}
}
use
var redVehicle = Vehicle ()
redVehicle.color = "Red"
redVehicle.maxSpeed = 90
redVehicle.travel () // output "Traveling at 90 kph" redVehicle.description () // = "A Red vehicle"
inherit
To override a function, to re-declare it in a subclass, and add the override keyword
class Car: Vehicle {
// Derived class can override function
override func description () -> String {
var description = super.description ()
return description + ", which is a car"
}}
In a rewritten function, which can be super callback function in the parent class version
override func description () -> String {
var description = super.description ()
return description + ", which is a car"
}
Initialization and deinitialization
class InitAndDeinitExample {
// Specified initializers (that is, the primary initializer)
init () {
print ( "I've been created!")
}
// Initialize the device easily, by calling the designated initializer required
convenience init (text: String) {
self.init () // This is required
print ( "I was called with the convenience initializer!")
}
// Anti-initializer
deinit {
print ( "I'm going away!")
}
}
var example: InitAndDeinitExample?
// Initialize the specified device
example = InitAndDeinitExample () // output "I've been created!"
example = nil // output "I'm going away"
// Initialize the device easy to use
example = InitAndDeinitExample (text: "Hello")
// Prints "I've been created!"
// Then output "I was called with the convenience initializer"
When you create a device initialization can return nil (also known as device initialization can fail), we put a question mark behind the init keyword and initialize the device determines that it can not successfully construct the object, use the return nil:
convenience init (value: Int)? {
self.init ()
if value> 5 {
// Can not initialize the object; returns nil, return nil indicates initialization failure
}}
When using a variable initialization device can fail, the results can be stored in any which are optional:
let failableExample = InitAndDeinitExample (value: 6)
// = Nil
protocol
The benefit of using the protocol that can be used Swift's type system to reference any object comply with a given agreement, individuals are now understood to be Interface concept.
protocol Blinking {
var isBlinking: Bool {get}
var blinkSpeed: Double {get set}
func startBlinking (blinkSpeed: Double) -> Void
}
class Light: Blinking {
var isBlinking = false
var blinkSpeed = 1.2
func startBlinking (blinkSpeed: Double) {
print ( "now my speed is (self.blinkSpeed)")
}
}
Spread
extension Int {
var doubled: Int {
return self * 2
}
func multiplyWith (anotherNumber: Int) -> Int {
return self * anotherNumber
}}
2.doubled // = 4
4.multiplyWith (32) // = 128
You can also use the extension to make a type of a compliance agreement
extension Int: Blinking {
var isBlinking: Bool {
return false;
}
var blinkSpeed: Double {
get {
return 0.0;}
set {
// Do nothing
}}
func startBlinking (blinkSpeed: Double) {
print ( "I am the integer (self). I do not blink.")
}}
2.isBlinking // = false
2.startBlinking (2.0) // output "I am the integer 2. I do not blink."
Access control
When a method or property declared as public, App to everyone can see it:
// Available for all to access
public var publicProperty = 123
// If a method or property declared as private, it can only be declared in its internal source files to see it:
// Can only be accessed in the source file
private var privateProperty = 123
// Only access for this module
// Here 'internal' is the default and can be omitted
internal var internalProperty = 123
Operator Overloading
Similar to C ++ operator overloading
class Vector2D {
var x: Float = 0.0
var y: Float = 0.0
init (x: Float, y: Float) {
self.x = x
self.y = y
}
}
func + (left: Vector2D, right: Vector2D) -> Vector2D {
let result = Vector2D (x: left.x + right.x, y: left.y + right.y)
return result
}
let first = Vector2D (x: 2, y: 2)
let second = Vector2D (x: 4, y: 1)
let result = first + second
Generics
Swift and Java generics same
class Tree {
// 'T' can now be used as a type var value: T
var value: T
var children: [Tree ] = []
init (value: T) {
self.value = value
}
func addChild (value: T) -> Tree {
var newChild = Tree (value: value)
children.append (newChild)
reutrn newChild
}
}
// Integer tree
let integerTree = Tree (value: 5)
// You can increase the subtree contains Int
integerTree.addChild (10)
// Use Swift Designer | 45
integerTree.addChild (5)
// String tree
let stringTree = Tree (value: "Hello")
stringTree.addChild ( "Yes")
stringTree.addChild ( "Internets")
String
Compare strings
let string1: String = "Hello"
let string2: String = "Hel" + "lo"
if string1 == string2 {
println ( "The strings are equal")
}
Find String
if string1.hasPrefix ( "H") {
println ( "String begins with an H")
}
if string1.hasSuffix ( "llo") {
println ( "String ends in 'llo'")
}
data
let stringToConvert = "Hello, Swift"
let data = stringToConvert.dataUsingEncoding (NSUTF8StringEncoding)
Swift with cocoa use Xcode development software
Open Xcode 7.2
Open Xcode choose New Project OSX Application

Open Main.storyboard, drag Label in the ViewController
 modify the code ViewController.swift
import Cocoa
class ViewController: NSViewController {
@IBOutlet Weak var timestamp: NSTextField!
@IBOutlet Weak var dateLabel: NSTextField!
@IBAction Func calc (sender: NSButton) {
// Input string to NSString
let string = NSString (string: self.timestamp.stringValue)
// Switch to double type
let ts: NSTimeInterval = string.doubleValue
// Conversion Date
let date = NSDate (timeIntervalSince1970: ts)
// Date format
let dfmatter = NSDateFormatter ()
dfmatter.dateFormat = "yyyy Year MM month dd day"
// Display the Label
dateLabel.stringValue = dfmatter.stringFromDate (date)
}
override func viewDidLoad () {
super.viewDidLoad ()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject {
didSet {
// Update the view, if already loaded.
}
}
}
NSTextField exclamation mark behind the above, it is called optional type implicit unpacking, is a special type, there may be noted that the value of the variable, or may be nil. Swift does not like to visit the operating environment variable is nil, therefore Swift programmer must be aware of the values of variables, especially when it may be nil.
Declare a variable implicitly opened optional type corresponds tell Swift compiler, you must promise not to access it at the value of the variable is nil. This is a contract that you signed with the compiler, you must comply. If you do not comply, the variable is nil when accessing it, will lead to the operational phase errors cause the application to stop running. |
|
|
|