你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS: 學習筆記, Swift操作符定義

iOS: 學習筆記, Swift操作符定義

編輯:IOS開發綜合

Swift操作符可以自行定義, 只需要加上簡單的標志符即可.

@infix 中置運算. 如+,-,*,/運算

@prefix 前置運算. 如-

@postfix 後置運算. a++, a--

@assignment 賦值運算. +=, -=, --a, ++a

//
//  main.swift
//  SwiftBasic
//
//  Created by yao_yu on 14-7-27.
//  Copyright (c) 2014年 yao_yu. All rights reserved.
//

import Foundation

struct Vector2D{
    var x = 0.0, y = 0.0
}

@infix func +(a:Vector2D, b:Vector2D) -> Vector2D{
    return Vector2D(x: a.x + b.x, y: a.y + b.y)
}

@infix func -(a:Vector2D, b:Vector2D) -> Vector2D{
    return a + -b
}

@prefix func -(a: Vector2D) -> Vector2D{
    return Vector2D(x: -a.x, y: -a.y)
}

@assignment func += (inout a: Vector2D, b:Vector2D){
    a = a + b
}

@prefix @assignment func ++(inout a:Vector2D){
    ++a.x
    ++a.y
}

@postfix func ++(a: Vector2D) -> Vector2D{
    return a + Vector2D(x: 1, y: 1)
}

@infix func ==(a:Vector2D, b:Vector2D) -> Bool{
    return (a.x == b.x) && (a.y == b.y)
}

@infix func !=(a:Vector2D, b:Vector2D) -> Bool{
    return !(a == b)
}

func Vector2D_Test(){
    var a = Vector2D(x: 1, y: 2), b = Vector2D(x: 3, y: 5)
    var c = a + b
    a += b
    println("(\(c.x), \(c.y))")
    println("(\(a.x), \(a.y))")
    assert(a == c, "a == b失敗")
    a += b
    assert(a != c, "a != b失敗")
    c = a++
    println("(\(a.x), \(a.y))")
    println("(\(c.x), \(c.y))")
}


Vector2D_Test()


  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved