swift——复合类型——函数——函数类型

本文探讨了Swift中的函数类型,包括它们如何作为返回类型和参数类型使用。函数类型的本质是一个元组,对于空元组可以使用Void或()表示,但不能省略。当元组仅有一个元素时,其括号可以是可选的,而多个元素时则不能省略。此外,函数类型在使用上与基本数据类型类似,可以被声明为常量或变量,并能进行类型推断。文中还提到了函数类型的参数和返回值,以及嵌套函数的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数类型

函数类型由参数类型和返回类型组成
func feed()
{
    print("feed nothing")
}

func feed(rice: Int) -> Int
{
    print("feed rice \(rice)")
    return rice;
}

func feed(rice: Int, meat: Int) -> (Int, Int)
{
    print("feed rice \(rice) and meat \(meat)")
    return (rice, meat)
}

func use_functype()
{
    let feed0: () -> Void = feed
    let feed1: (Int) -> Int = feed
    let feed2: (Int, Int) -> (Int, Int) = feed
    
    feed0();
    feed1(5)
    feed2(5, 8)
}
output:
feed nothing
feed rice 5
feed rice 5 and meat 8
总结:
  • 函数类型的返回类型本质为tuple,因此空tuple可用Void或()表示,但不可omit,只含单个成员tuple括号optional,包含多个成员tuple括号不可omit
  • 函数类型的参数类型本质为tuple,因此空tuple可用Void或()表示,但不可omit,只含单个成员tuple括号optional,包含多个成员tuple括号不可omit
  • 函数类型在使用上与普通类型(如Int)无任何区别,可使用let或var定义,亦可进行类型推断,只要不造成二义性error
  • 函数名本质就是函数类型,只是常量(let)而已,函数定义时即进行了初始化,指向所定义函数

函数类型参数

func add(a: Int, _ b: Int) -> Int
{
    return a + b
}

func sub(a: Int, _ b: Int) -> Int
{
    return a - b
}

func arith(fun: (Int, Int) -> Int, _ a: Int, _ b: Int)
{
    print("result: \(fun(a, b))")
}

func functype_param()
{
    arith(add, 18, 8)
    arith(sub, 18, 8)
}
output:
result: 26
result: 10

函数类型返回值

func add(a: Int, _ b: Int) -> Int
{
    return a + b
}

func sub(a: Int, _ b: Int) -> Int
{
    return a - b
}

func arith(flag: Bool) -> (Int, Int) -> Int
{
    if(flag)
    {
        return add
    }
    else
    {
        return sub
    }
}

func functype_ret()
{
    let fun1 = arith(true)
    let fun2 = arith(false)
    
    print("result: \(fun1(18, 8))")
    print("result: \(fun2(18, 8))")
}
output:
result: 26
result: 10

嵌套函数

func arith(flag: Bool) -> (Int, Int) -> Int
{
    func add(a: Int, _ b: Int) -> Int
    {
        return a + b
    }
    
    func sub(a: Int, _ b: Int) -> Int
    {
        return a - b
    }
    
    if(flag)
    {
        return add
    }
    else
    {
        return sub
    }
}

func nested_func()
{
    let fun1 = arith(true)
    let fun2 = arith(false)
    
    print("result: \(fun1(18, 8))")
    print("result: \(fun2(18, 8))")
}
output:
result: 26
result: 10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值