swift Swift中的变量

Swift中的变量以关键字“let”开头。 <br/> <br/>常量的名称以小写字母开头。如下面的示例所示,它们可以包含几个单词,所有单词都在一起运行。那是因为如果两者之间有空格,Swift会认为每个单词都是不同的标识符。 <br/> <br/>为了便于阅读包含多个单词的标识符,第一个单词后面的每个单词都应该大写。这种写出名字的方式称为驼峰案例,因为名称中间的大写字母看起来有点像骆驼的驼峰。 <br/>当你在Swift中定义一个常量时,它被称为声明一个常量。所以上面的陈述被称为声明。 “我声明名称numberOfDogs的值为101!”。 <br/> <br/>单词let是关键字的一个示例。关键字在Swift中具有特殊含义,不能用作名称。 let关键字用于声明常量。随着时间的推移,您将了解更多Swift关键字。

Variables
let naamVariabele = 5 

swift 如果 - 插图

ifLetDemo
class Cat {
	func sayHello() -> String {
		return "Meow!"
	}
}

func schrodingersCat() -> Cat? {
	// Open the box!
	let cat = [0, 1].randomElement()
	
	if cat == 1 {
		return Cat() 
	}
	else {
		return nil
	}
}

if let kitty = schrodingersCat() {
	print(kitty.sayHello())
}
else {
	print("Poor kitty.")
}

swift debug print vs print

.swift
If You make a network call and do a debugPrint(response) instead of print(response), you will get a lot more valuable information. See the below example code:

Sample Code : Using iTunes Search Api
    let urlReq = URLRequest(url: URL(string: "https://itunes.apple.com/search?term=jack+johnson&limit=1")!)

    Alamofire.request(urlReq).responseJSON { (data) in
        print(data)
        print("\n\n\n\n\n\n\n\n\n")
        debugPrint(data)
    }
    
Console Output (Removing some of the response fields)

/////////////////////////For print//////////////////////////////
SUCCESS: {
    resultCount = 1;
    results =     (
                {
            artistId = 909253;
            artistName = "Jack Johnson";
            artistViewUrl = "https://itunes.apple.com/us/artist/jack-johnson/id909253?uo=4";
        }
    );
}
////////////////////// For debugPrint //////////////////////////////////////
[Request]: GET https://itunes.apple.com/search?term=jack+johnson&limit=1
[Response]: <NSHTTPURLResponse: 0x610000223860> { URL: https://itunes.apple.com/search?term=jack+johnson&limit=1 } { status code: 200, headers {
    "Access-Control-Allow-Origin" = "*";
    "Cache-Control" = "max-age=86345";
    Connection = "keep-alive";
    "Content-Disposition" = "attachment; filename=1.txt";
    "Content-Length" = 1783;
    "Content-Type" = "text/javascript; charset=utf-8";
    Date = "Sat, 23 Sep 2017 14:29:11 GMT";
    "Strict-Transport-Security" = "max-age=31536000";
    Vary = "Accept-Encoding";
    "X-Apple-Partner" = "origin.0";
    "X-Cache" = "TCP_MISS from a23-76-156-143.deploy.akamaitechnologies.com (AkamaiGHost/9.1.0.4-20866905) (-)";
    "X-Cache-Remote" = "TCP_MISS from a23-45-232-92.deploy.akamaitechnologies.com (AkamaiGHost/9.1.0.4-20866905) (-)";
    "X-True-Cache-Key" = "/L/itunes.apple.com/search ci2=limit=1&term=jack+johnson__";
    "apple-originating-system" = MZStoreServices;
    "apple-seq" = 0;
    "apple-timing-app" = "86 ms";
    "apple-tk" = false;
    "x-apple-application-instance" = 1000492;
    "x-apple-application-site" = NWK;
    "x-apple-jingle-correlation-key" = VEF3J3UWCHKUSGPHDZRI6RB2QY;
    "x-apple-orig-url" = "https://itunes.apple.com/search?term=jack+johnson&limit=1";
    "x-apple-request-uuid" = "a90bb4ee-9611-d549-19e7-1e628f443a86";
    "x-apple-translated-wo-url" = "/WebObjects/MZStoreServices.woa/ws/wsSearch?term=jack+johnson&limit=1&urlDesc=";
    "x-content-type-options" = nosniff;
    "x-webobjects-loadaverage" = 0;
} }
[Data]: 1783 bytes
[Result]: SUCCESS: {
    resultCount = 1;
    results =     (
                {
            artistId = 909253;
            artistName = "Jack Johnson";
            artistViewUrl = "https://itunes.apple.com/us/artist/jack-johnson/id909253?uo=4";
        }
    );
}

[Timeline]: Timeline: 

{
  "Request Start Time": 527869893.013,
  "Initial Response Time": 527869893.033,
  "Request Completed Time": 527869893.034,
  "Serialization Completed Time": 527869893.035,
  "Latency": 0.020secs,
  "Request Duration": 0.021secs,
  "Serialization Duration": 0.001secs,
  "Total Duration": 0.021secs
}

swift 反向布尔值

.swift
1.) using toggle function
var isVisible = true
print(isVisible.toggle())  // false

2.) using ! is the "logical not" operator:
var x = true
x = !x
print(x) // false

swift 独生子

.swift
class Singleton {
    var name = "sumit"
    static let shared = Singleton()
    
    private init() {
        // don't forget to make this private
    }
}
let singleton = Singleton.shared
let A = Singleton.shared
let B = Singleton.shared
print(A.name)
print(B.name)

A.name = "Ankit"
print(A.name)
print(B.name)

swift 获得数组的独特元素

.swift
arr = Array(Set(arr))

swift 获得数组的独特元素

.swift
arr = Array(Set(arr))

swift struct,NSArray,NSMutableArray

.swift
1. Struct
// Importance of struct: Sensor is struct so that appending in array can be done with value not by reference
struct MotionSensor {
    var dateFormatter = DateFormatter() // to convert date into string
    init(newFormatter: DateFormatter)
    {
        self.dateFormatter = newFormatter
    }
    
    func toString() -> String
    {
    }
  }
2. Class
class LocationSensorData
{
    var arr = [LocationSensor]()
    var i = 0
    init()
    {
        //iniitalization
        
    }
    
    func toString() -> String{
        var myString = ""
        for sensor1 in arr
        {
            myString += sensor1.toString() + "\n"
            //            print("\(self.i)  : \(sensor1.actionType!)")
            //            self.i = self.i + 1
            
        }
        
        return myString
    }
    
}

3. NSArray,NSImmputable Array
In contrast, a Foundation NSArray is immutable by default. If you want to add, 
remove or modify items after creating the array, you must use the mutable variant class NSMutableArray
An NSArray is heterogeneous, meaning it can contain Cocoa objects of different types. Swift arrays are homogeneous, meaning that each Array is guaranteed to contain only one type of object
However, you can still define a single Swift Array so it stores various types of Cocoa objects by specifying that the one type is AnyObject, since every Cocoa type is also a subtype of this.


4. Swift array
Swift arrays are immutable if you define them as constants with let, and mutable 
if you define them as variables with var.

swift 特定索引处的数组元素

.swift
var arr = [34,534,634,345,234]
let indexes = [0,3,4]
arr = indexes.compactMap{ arr[$0] } // [34, 345, 234]

swift 阵列的中位数

.swift
extension Array where Element == Int {
    func median() -> Double? {
        guard count > 0  else { return nil }

        let sortedArray = self.sorted()
        if count % 2 != 0 {
            return Double(sortedArray[count/2])
        } else {
            return Double(sortedArray[count/2] + sortedArray[count/2 - 1]) / 2.0
        }
    }
}

let arr = [1,2,3,4,5,6,7,8,9]
if let median = arr.median() {
    // do something
}