LoginSignup
14

More than 5 years have passed since last update.

【はじめてのSwift】基本的な関数の書き方

Last updated at Posted at 2014-08-19

関数の作り方

一番基礎となる形

A.swift
func favoritePlace(placeName: String) -> String {
    return "I like " + placeName + "."
}

println(favoritePlace("Okinawa"))
// "I like Okinawa." と出力

上記関数は以下のような形。

A.swift
func 関数名 (パラメータ: ) -> 返り値の型 {
    return 返り値
}

複数のパラメータを持つ関数

B.swift
func relationship(s1: String, s2: String, relation: String) -> String {
    return s1 + relation + s2
}
B.swift
func 関数名パラメータ1: パラメータ1の型, パラメータ2: パラメータ2の型, パラメータ3: パラメータ3の型) -> 返り値の型 {
    return 返り値
}

このrelationshipという関数は以下のように呼び出す

relationship("Taro", "Hanako", "likes")
// "Taro likes Hanako"と出力

また、可読性を高めるために以下のように関数を書き換えることも可能。

B.swift
func relationship(man s1: String, woman s2: String, relation joiner: String) -> String {
    return s1 + joiner + s2
}

relationship(man: "Taro", woman: "Hanako", relation: "loves")
// "Taro loves Hanako"と返ってくる

さらに、パラメータ名を省略して書くことも可能。

B.swift
func relationship(#man: String, #woman: String, #relation: String) -> String {
    return man + relation + woman
}

このように書くことで可読性を維持したまま、コード量も省略できる。

relationship(man: "Taro", woman: "Hanako", relation: "hates")
// "Taro hates Hanako"と返る

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
14