• iOS: 学习笔记, Swift运算符定义


    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()
  • 相关阅读:
    APP-SQLAP-10771:Could not reserve record (匹配PO时候)
    EBS常用小常识(转)
    ajax-工作原理,包含技术,缺陷
    js实现“级联菜单”
    考证
    十八大以来习主席同志关于经济工作的重要论述
    局域网使用打印机的快捷方法
    修改JRE system library
    十步完全理解SQL
    2013读书笔记
  • 原文地址:https://www.cnblogs.com/yaoyu126/p/3872148.html
Copyright © 2020-2023  润新知