Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftで関数定義いろいろ

Posted at

練習みたいなもんです。
これを使ってどうこうみたいな話ではありませんのであしからず。

classで

swift
import Cocoa

class SomeOps {
   	func add(a:Int,b:Int) -> Int { return a+b }
   	func sub(a:Int,b:Int) -> Int { return a-b }
   	func mul(a:Int,b:Int) -> Int { return a*b }
   	func sur(a:Int,b:Int) -> Int { return a%b }
}

let ops = SomeOps()
ops.add(1,b:2)
ops.sub(1,b:2)
ops.mul(1,b:2)
ops.sur(1,b:2)

普通な感じ。

enumで

swift
import Cocoa

enum SomeOps {
    case add,sub,mul,sur
    func proc(a:Int,b:Int)->Int {
        switch self {
            case .add: return a+b
	        case .sub: return a-b
	        case .mul: return a*b
	        case .sur: return a%b
   	    }
   	}
}

SomeOps.add.proc(1,b:2)
SomeOps.sub.proc(1,b:2)
SomeOps.mul.proc(1,b:2)
SomeOps.sur.proc(1,b:2)

期待した形にはならなかった・・・。
僕が何か遠回りをしてるのかも。

funcを返すfuncで

swift
import Cocoa

func makeSomeOps() -> Dictionary<String,(Int,Int) -> Int> {
    return [
        "add":{ (a:Int,b:Int) -> Int in return a+b },
        "sub":{ (a:Int,b:Int) -> Int in return a-b },
        "mul":{ (a:Int,b:Int) -> Int in return a*b },
        "sur":{ (a:Int,b:Int) -> Int in return a%b },
    ]
}

let ops = makeSomeOps()
ops["add"]!(1,2)
ops["sub"]!(1,2)
ops["mul"]!(1,2)
ops["sur"]!(1,2)

綺麗な気はするけど別に使いたくはならない。
b:って書かなくて良いところはいいかも。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?