let
var a = 10 //
let b = 20 //Constant 一度だけ割り当てられ、変更できない。
print(a,b)///10 20
a = 30
print(a)///30
b = 50 ///値に割り当てられない: 'b' is a 'let' constant
//初期化時の定数は使用できない
基本データ型
- IntFloat, Double, Bool, Character, String
- Array辞書, タプル
- データ型の最初の文字は大文字で、異なる型の2つの値を直接計算することはできません。
型のエイリアス
typealias SK = Int
let i:SK = 666
print(i)
typealias Block = (_ age:Int)->()
let myBlock : Block
タイプ変換
let str: String = "10"
let a = Int(str)
let str: String = "10"
let a = Double(str)
let a: Int = 20
let str = String(a)
let a: Int = 20
let b = Double(a)
let a: Double = 3.14
let str = String(stringInterpolationSegment: a)
let a: Double = 3.14
let b = Int(a)
??
//オブジェクトがnilの場合、それに続く値が代わりに使われるが、元の変数は変更されない。
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
オプションの型とオプションの型の値
//オプションの型定義
var newName : String?
newName = "swift"
print(newName)///Optional("swift")
let dictionary = ["name":"objective"]
let item = dictionary["name"]
print(item)///Optional("objective") オプション 使用不可
//
///1.強制アンパッキング
print(newName!,item!)///swift objective
///推奨しない nullの値はクラッシュする
let itemS = dictionary["nil"]
print(itemS)///nil クラッシュしない
//print(itemS!)///クラッシュ Thread1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
///オプションのバインディング
if let item = item {
print(item)///objective
}
///2. ??
print(item ?? "デフォルト")////目的語
///3.guard
guard let new = item else {
return//条件が満たされていなければ、そのままリターンする。 条件が満たされていれば、次のコードを実行し続ける。
}
print(new)///objective
タプル
///タプルの定義
var yz = ("he",true,"swift",15)//var変数は値を変えることができる
let h :(Int,String) = (66,"swift")///let型を変更できないことを指定する。
let c = (age:10,name:"swift")
let (age,name) = (22,"sk")
///
let itemYZ = yz.1
let itemH = h.1
let itemC = c.name
///
yz.1 = false
print(age,name)///22 sk
print(itemYZ,itemH,itemC)///true swift
配列
///
let array = ["1","2","3"]///不変配列
var mArray = Array<String>()///変数配列
var selectArray : Array<Dictionary<String,Any>> = []///辞書付き変数Null配列
///配列の操作 - 変異可能な配列の場合
//1.要素を追加する
mArray.append("First")
mArray.append("Second")
mArray.append("Third")
print(array,mArray)///["1", "2", "3"] ["First", "Second", "Third"]
//2.要素を削除する
mArray.remove(at: 1)
print(mArray)///["First", "Third"]
//3.要素を取得する
let item = mArray[0]
print(item)///First
//4.要素を修正する
mArray[0] = "edit First"
print(mArray)///["edit First", "Third"]
//5.
for item in mArray {
print(item) ///edit First第三
}
for item in mArray[0..<1] {///指定された区間を反復する
print(item) ///edit First
}
for (index,value) in mArray.enumerated() {
print(index,value)///0 edit First 1 Third
}
///配列内のモデルオブジェクトを繰り返し処理する
let watch_list = NSMutableArray.init()//oc 変数配列
let array = CommonDataManage.sharedManager().watchBindArray
if let modelArray = array as? [ContectWatchModel] {
for model in modelArray {
watch_list.add(["watch_userid":NSNumber.init(value: Int(truncating: model.watch_userid))])
}
}
辞書
let dic:[String:Any] = ["name":"s","age":10]
let dictionary = ["name":"swift","age":"10"]///
print(dic,dictionary)//1.["age": 10, "name": "s"]2.["age": "10", "name": "swift"]
var dicM = [String : Any]()///
///要素を追加する
dicM["height"] = 20
dicM["name"] = "objective"
print(dicM)///["name": "objective", "height": 20]
///要素を削除する
dicM.removeValue(forKey: "name")
print(dicM)///["height": 20]
///要素を修正する
dicM["height"] = 178
print(dicM)///["height": 178]
///要素の取得
let item = dicM["height"]
print(item!)///178
///要素を繰り返し処理する
dicM["weight"] = 108
dicM["age"] = 28
for key in dicM.keys {
print(key)///age height weight
}
for value in dicM.values {
print(value)///28 178 108
}
for (key,value) in dicM {
print(key)
print(value)
}
文字列
///1.空の文字列
var string = ""
print(string)
if string.isEmpty {
print("空の文字列!")//// を実行する
}
string = "swift"
print(string)//swift
///2.文字列を定義する 初期値はnil 後日割り当て可能
var str : String?
/*
if str.isEmpty {///オプションの型'String'のエラー値?' must be unwrapped to refer to member 'isEmpty' of wrapped base type 'String'
print("空の文字列!")
}
*/
str = "objective"
print(str ?? "")///objective
///3.
let str_1 = "a little"///swiftはString型そのものを推論する
print(str_1)///a little
///4.複数行表示
let softWrappedQuotation = """
1. swift
2. あなたはいい人生を送っている。
3. ハロウィンを理解する
"""
print(softWrappedQuotation)
/*
1. swift
2. あなたはいい人生を送っている。
3. ハロウィンを理解する
*/
///5.
let open_swift = "openswift"
for c in open_swift {
print(c)///個々のキャラクター
}
///6.文字列比較
/*
1.文字列と文字の等価性 (== !=)
2.接頭辞の等号 hasPrefix(_:)
3.サフィックスの等号 hasSuffix(_:)
*/
///7.文字列スプライシング
let a = 10
let c:String = "hello"
let h:String = c + "\(a)"
print(h) //hello10
注釈
// 一行コメント
/*複数行コメント*/
クロージャ
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
///1.クロージャ式による関数の定義
let sum = {
/// + +戻り値のタイプ+in+関数本体コード
(num1: Int, num2: Int) -> Int in
return num1 + num2
}
let result = sum(5,5)
print(result)//10
///2.関数のパラメータとして コールバック
callBck { (dictionary) in
print(dictionary)///["key": "10"]
}
///3.末尾のクロージャは、関数の括弧の後に書かれるクロージャ式で、関数が最後の引数として呼び出すことをサポートする。
callBck { (dic) in///注:関数がクロージャ式の引数を1つしか取らない場合、末尾のクロージャを使うときに()を省略することもできる。
print(dic)///["key": "10"]
}
}
typealias SumBlock = (Dictionary<String, String>) -> ()
func callBck(block:SumBlock)///類似Webリクエストのコールバック結果
{
let dictionary = ["key" : "10"]
block(dictionary)
}
}
機能
//関数定義
///1.戻り値なし
func initUI(title : String) {
}
///2.戻り値を持つ
func callTitle(title : String) -> String {
return title + "チェンジ!"
}
///3.パラメータなし 返り値なし
func blindWatch() {
}
///4.変数パラメータ
//callName("hello", "swift", "php", "applet")を呼び出す。,"fluute","web")
func callName(_ name:String...) {
var totalStr = ""
for str in name {
totalStr += str
print(str)/// 入ってきた引数をそれぞれ表示する hello swift php applet fluute web
}
print(totalStr)///helloswiftphpアプレット fluuteweb
}
///5.ネストされた関数 関数の中に関数を定義する
///6. inout 本質的なアドレス渡しは、パラメータのみを変更する必要があるため、inoutキーワードを使用し、関数に&
/*
func sd_change(name : String) {
name = "new_" + name//エラー報告 パラメータのデフォルトはletで、変更できない。
}
*/
// var名を呼び出す= "swift" sd_change(name: &name)
func sd_change(name : inout String) {
name = "new_" + name //swift関数のパラメータのみを変更する必要がある場合は、inout キーワードを使用し、その関数を&
print(name)
}
列挙
import UIKit
/*
OC
列挙型はInt型のみである
swift :
メソッドは列挙型で定義できる
ケースの型がInt、Double、Stringなどであることを宣言できる。
関連する値を使用することが可能である。
rawValueを使って値を取ることができるが、型を宣言しなければならない。
init(rawValue:)列挙型を作成するが、型を宣言する必要がある
*/
enum PustType {
case commonPushType
case historyPushType
case recordPushType
}
/*----は次のように省略できる。
enum PustType {
case commonPushType, historyPushType, recordPushType
}
*/
///String
enum Week: Int{
case MON, TUE, WED, THU, FRI, SAT, SUN
}
enum Season {
case spring,summer,autumn,winter
}
///
enum Shape{
case circle(radius: Double)
case rectangle(width: Int, height: Int)
}
enum Code{
case num(Int,Int,Int)
case str(String,String)
}
class ViewController: UIViewController {
var type : Shape?///一般的な使い方 プロパティの定義 外部からの受け渡し
override func viewDidLoad() {
super.viewDidLoad()
///switchステートメントの解析
switch self.type {
case .circle:
print("the shape is circle")
case .rectangle:
print("the shape is rectangle")
case .none:
print("nil")
}
///fuzhi
let code = Code.str("A", "B")
print(code)//str("A", "B")
///rawValue
let week = Week(rawValue: 2)
print(week ?? "nil")///WED
}
}
オプションのバインディング
///
let dic :Dictionary<String,String>? = ["key":"value"]
print(dic as Any) //Optional(["key": "value"])
//let value = dic["key"] ///原因dicはオプションの型である
if let dic = dic,let value = dic["key"] {
print(dic)//["key": "value"]
print(value)//value
}
///
let adress: String? = "杭州"
print(adress)//Optional("杭州")
if let adress = adress {
print(adress)//杭州
}
///
let a: Int? = 10
guard let value = a else {
return
}
print(value)
guard
///オプションのアンラッピング
let dictionary = ["name":"swift"]
let item = dictionary["name"]
print(item)///Optional("swift") オプション 使用不可
guard let new = item else {
return//条件が満たされていなければ、そのままリターンする。 条件が満たされていれば、次のコードを実行し続ける。
}
print(new)///swift
if
let dic : Dictionary<String,String> = ["name":"Tom","age":"18","id":"60018"]
let name = dic["name"]
if name == "Tom" {
print("トムを見つけた")
}else if(name == "cat")
{
print("猫を見つけた")
}else
{
print("猫とトムが見つからない")
}
swich
///一般的な使い方
let watch_id : Int? = 2
switch watch_id {
case 0:
print("ID 0用")
case 1:
print("ID 1 "の場合)
case 2,3:
print("ID が2であるか3であるか")
fallthrough//全体を通して 次の分岐では
default:
print("case")
}
///whereを組み合わせる
let somePoint = (1, -1)
switch somePoint {
case let(x, y) where x == y:
print("1")
case let(x, y) where x == -y:
print("2")
case let(x, y):
print("3")
}
三項演算子
//a,bの最大値を取る
let a = 20
let b = 30
let c = a > b ? a : b
print(c)///30
for
let array = ["健康」「幸せ」「気質」「自信」「裕福」「平和」「長寿]
for title in array {
print(title)///一枚ずつ印刷する
}
let array_two : [Int] = [10, 20, 30]
for id in array_two {
print( "index の値は\(id)")///一枚ずつ印刷する
}
属性
import UIKit
var allCan : String = "my_swif"///グローバル変数
class ViewController: UIViewController {
///1.アトリビュートの保存は、現在のインスタンス・オブジェクトのメモリを占有する方法である。
var age : Int = 18
var nurse_userid : String?///プロパティを定義する
///2.プロパティの計算が現在のインスタンス・オブジェクトのメモリを消費しない
var width: Double = 8.0
var area: Double {
get {
return width * width
}
set (newValue){
width = sqrt(newValue)
}
}
var width_new: CGFloat {
get { return self.view.frame.size.width }
set { self.view.frame.size.width = newValue }
}
///3.Lazy 属性Deferredストレージは、最初にアクセスされたときに値が割り当てられる。
lazy var ske_id : String = "60001"///注:インスタンス構築の完了時にプロパティの値が利用できない可能性があるため、遅延ストレージ・プロパティは変数として宣言されなければならない。一方、定数プロパティは、構築プロセスの完了時に初期値を持たなければならないため、遅延プロパティとして宣言することはできない。
/*
遅延ストアはデフォルトの初期値を持たなければならない。
Deferredストレージは、最初にアクセスされるまで値が割り当てられない。
ディファード・ストレージ属性はインスタンス・オブジェクトのサイズに影響を与える。
遅延記憶属性はスレッドセーフではない。
*/
///4.型属性staticは一度だけ初期化される
static var weight: Int = 115
override func viewDidLoad() {
super.viewDidLoad()
self.nurse_userid = "600028"
print(self.age,self.nurse_userid ?? "123")///18 600028
print("エリアは"+ "\(self.area)")
print("画面の幅は:" + "\(self.width_new)")
print(self.ske_id)//lazy 属性60001
}
}
属性リスナー
var counter: Int = 0{
willSet(newTotal){
print("willSet: \(newTotal)")
}
didSet{
if counter > oldValue {
print("didSet \(counter - oldValue)")///引き算
}
}
}
counter = 20
counter = 88
/*
willSet: 20
didSet 20
willSet: 88
didSet 68
*/