Swift_关键字static和class的区别

阻容降压 vs 开关电源:5V小功率供电方案成本与安全深度对比 本文深度对比了阻容降压电路与开关电源在5V小功率供电方案中的核心差异。重点剖析了二者在成本、体积、效率、温升及安全隔离等方面的优劣,并结合智能温控器、LED驱动等典型应用场景,为硬件工程师提供了清晰的选型决策框架,帮助在成本与安全之间做出最佳权衡。 阅读详情
  • 说明:

  • 此文章由 @春雨 编写. 经 @Scott 审核. 若转载此文章,请注明出处和作者

代码


import UIKit


class Person {

    // 给方法添加class关键字
    class func work() {
        print("Type Method: Person: 警察.")
    }

    // 使用static关键字创建类方法
    static func nameOfPerson(name: String) {
        print("Type Method: Person name: \(name)")
    }

    // 可以和类方法重名, 以及一样的参数.
    func nameOfPerson(name: String) {
        print("Instance Method: person name \(name)")
    }

}

class Teacher: Person {

    // 重写父类的类型方法.
    override class func work() {
        print("Type Method: Teacher: University Teacher")
    }



    /**
     * 下面的写法是错误的, 报错信息: Class method overrides a 'final' class method(重写了一个final的类方法.)
     * final 关键字:
     可以通过把方法,属性或下标标记为final来防止它们被重写,只需要在声明关键字前加上final修饰符即可(例如:final var,final func,final class func,以及final subscript)。如果你重写了final方法,属性或下标,在编译时会报错。

     */
//    override static func nameOfPerson(name: String) {
//
//    }




}

class Student: Person {

    // 子类Student的实例方法work(), 和父类的类方法work()没有关系, 二者不在同一个级别上, 不存在同名问题.
    func work() {
        print("Instance Method: Student: University Student")

    }
}



class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let per = Person()
        // 父类的类方法
        Person.work()  /**< Type Method: Person: 警察. */
        Person.nameOfPerson("Tom") /**< Type Method: Person name: Tom */
        // 父类的实例方法
        per.nameOfPerson("Edward") /**< Instance Method: person name Edward. */


        // 子类的类方法

        // 直接调用父类的类方法
        Teacher.nameOfPerson("Susan") /**< Type Method: Person name: Susan */
        // 调用的是子类中重写父类的类方法work()
        Teacher.work() /**< Type Method: Teacher: University Teacher */


        let stu = Student()
        // 子类Student的实例方法work()
        stu.work() /**< Instance Method: Student: University Student */



    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


总结

1. 关键字static和class的区别

在方法的func关键字之前加上关键字static或者class都可以用于指定类方法.
不同的是用class关键字指定的类方法可以被子类重写, 如下: 
    override class func work() {
    print("Teacher: University Teacher")
}

但是用static关键字指定的类方法是不能被子类重写的, 根据报错信息: Class method overrides a 'final' class method. 
我们可以知道被static指定的类方法包含final关键字的特性--防止被重写. 

2. 类方法和实例方法可以重名.

不建议写相同的方法名. 

Oracle 查看 rman 备份情况 SQL 语句 每天一个 DBA 小知识,助你更进一步! 阅读详情

相关推荐

NVIDIA DGX Spark (Ubuntu 24.04) 部署Isaac Sim与Isaac Lab:二进制安装与ROS2集成实战

本文详细介绍了在NVIDIA DGX Spark工作站(Ubuntu 24.04系统)上,通过预编译二进制包稳定部署Isaac Sim与Isaac Lab的完整实战流程。文章重点剖析了二进制安装相较于源码编译和pip安装的优势,有效规避了CUDA、PyTorch等关键组件的版本冲突陷阱,并逐步指导完成环境配置、Isaac Lab集成、Conda环境管理以及ROS2 Jazzy的集成,最终构建出完整的机器人仿真与强化学习开发平台。

kite3的博客 396

swift中static关键字用法,static与class关键字的区别详解

首先swift中的static同样具有类属性和类方法的特性,这点和很多语言类似,在Swift中,static关键字用于定义类型方法或类型属性,这些方法或属性属于类型本身,而不是类型的实例。这意味着你可以在不创建类型实例的情况下访问它们。

j15087159186的博客 1116

使用Matlab进行IEEE 33节点潮流计算的NR法实现详解及应用实例

IEEE 33节点系统是一个标准的配电系统模型,广泛用于学术研究和工程应用。该系统由33个节点和37条线路组成,结构复杂,具有代表性。其潮流计算结果可用于验证各种潮流计算方法的准确性和效率。NR法是一种基于迭代求解的潮流计算方法,通过不断迭代求解非线性方程组,直到达到预定的收敛条件。NR法具有收敛速度快、计算精度高的优点,适用于大规模复杂电力系统的潮流计算。

m0_57781768的博客 2070

swift class func和static func

Swift中class func与static func的区别

baidu_40537062的博客 1085

Xilinx Aurora 8B/10B IP核详解和仿真

Xilinx Aurora 8b/10b IP核的详解,以及使用与仿真示例,对IP核的配置和如何仿真有非常详细的说明,除了对IP核官方文档的内容进行了解析以外,还对GTX引脚的选择等比较容易混淆和不好理解的地方进行了说明。最后对IP核的仿真运行进行了STEP BY STEP 的说明,对仿真的结果也进行了简要的说明。 该文档对Xilinx FPGA和ZYNQ SOC下 AURORA 8B/10B IP核的使用提供了一个快速上手的指导。

weixin_43354598的博客 1万+

OpenClaw 完整命令文档(2026.3.13 最新版)

本文档为OpenClaw 2026.3.13通用版使用指南,包含核心命令大全。主要内容包括:1)基础安装/升级/卸载命令;2)ClawHub扩展安装命令(支持飞书/钉钉/企微等平台连接);3)Skills技能安装命令(实现聊天/搜索/记忆等功能);4)飞书机器人授权与配对命令;5)启动运行与配置检查命令;6)工作区与记忆管理命令;7)插件安全设置命令;8)调试日志命令;9)飞书机器人一键部署简化流程。文档特别强调飞书机器人部署需feishu扩展+对应技能+用户授权的完整配置,所有命令均需在终端执行,安装后需

MKliudan的专栏 1290

静态内部类(public static class)和普通内部类(public class)的区别

一、static修饰 java中普通的顶级类是不能使用static关键字修饰的。 只有内部类可以使用static修饰,或者不使用staitc关键字修饰。 // 顶层类A不能用static修饰 public class A{ // 普通内部类B, 可以不用static修饰 public class B{ } // 普通内部类C, 也可以用static修饰 public static class C{ } } 二、引用区别 1、静态内部类(s

文盲青年的博客 5801

ERA5气象数据下载与解压全攻略:Python脚本一键搞定(附错误处理技巧)

本文提供了一套完整的ERA5气象数据自动化处理方案,涵盖从CDS API配置、智能批量下载到高效解压与数据验证的全流程。重点介绍了如何通过Python脚本实现一键式数据下载与批量解压,并分享了实用的错误处理技巧与性能优化策略,帮助科研人员高效获取和处理大规模气象数据。

k8l9m0n的博客 337

深入理解Swift中static和class关键字

static和class 作用:这两个关键字都是用来说明被修饰的属性或者方法是类型(class/struct/enum)的,而不是类型实例的。 static 适用的场景(class/struct/enum) 修饰存储属性 修饰计算属性 修饰类型方法 struct Point { let x: Double let y: Double // 修饰存储属性 static let zero = Point(x: 0, y: 0) // 修饰计算属性 s.

box_kun的博客 848

不会精准对比前人研究写“讨论与对比”段落?教你用ChatGPT辅助,直接让这部分提升一个档次(附提示词指令)

一个我觉得很有效的做法是,选取几篇具有代表性的文献,从研究方法、变量设置或结论方面进行对照分析,并指出本研究在哪些方面进行了补充或修正。除了简单说“提出了新的方法”或“首次应用某模型”,更需要说明这一做法在结果解读、研究设计或理论拓展上的具体意义,最好能够与现有研究进行比较,形成明确的差异化描述。段落应包含:研究结果解释、与前人研究对比、研究贡献、局限性反思,并在结尾提出未来研究的可能方向。讨论与对比部分一般位于文献综述、研究讨论或结果分析的后面,目的是对比已有研究,突出自己研究的价值与新意。

智能AI让学术科研更容易 170

【国产MCU】-CH32V307-通用定时器(GPTM)-输入捕获模式测量脉冲

CH32V307的通用定时器模块包含一个16 位可自动重装的定时器(TIM2、TIM3、TIM4和TIM5),用于测量脉冲宽度或者产生特定频率的脉冲、PWM波等。可用于自动化控制、电源等领域。 输入捕获是通用定时器功能之一,一般用于测量频率和测量脉冲宽度。本文将详细介绍如何通用定时器的输入捕获功能。

视觉与物联智能 2814

Swift中的静态函数和类函数有什么区别?

I can see these definitions in the Swift library: 我可以在Swift库中看到这些定义: extension Bool : BooleanLiter

xfxf996的博客 1042

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Swift 类中 属性和func 的 class 和 static 关键字区别

  区别在于:   static  定义的属性和func 没办法被子类 override   class 定义的属性和func 可以被子类 override.

tangaowen的专栏 1086

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Swift - class与staitc关键字的区别与使用

一、static 关键字 1,结构体 struct 和枚举 enum 的静态属性,静态方法使用 static 关键字 struct Persion { var name :String = "" var age :Int = 0 static var intersetRate :Double = 10 static func in...

cym_bj 416

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Swift - static 和 class

Swift 中表示“类型范围作用域”这一概念的有两个不同的关键字,它们分别是static 和 class。这两个关键字确实都表达了这个意思,但是在其他一些语言,包括Objective-C中,我们并不会特别的区分类变量/类方法和静态变量/静态函数。但是在Swift中,这两个关键字却是不能用混的。 static 在非class类型上下文中,我们统一使用static来描述类型作用域,包括在enum 和struct 以及class中表述类型方法和类型属性时。在这两个值类型中,我们可以在类型范围内声明并使用存储属性、

HumorousGhost 1137

swift 里的class和static

啊

chmashin的博客 882

Swift 关键字

一、swift中的权限关键字:open,public, fileprivate, private:open 该权限是最大的权限,允许访问文件,同时允许继承 public 允许访问但不允许继承 fileprivate 允许文件内访问 private 只允许当前对象的代码块内部访问作者:老马的春天 链接:http://www.jianshu.com/p/88d756f81fa9

Quinn's blog ! I'm glad to be here! 973

ios开发 swift中类方法 用class还是static

在 Swift 中,类方法可以使用class或static关键字来定义,但它们有一些关键的区别:

937

swift: Swift中static和class的使用

Swift中表示 “类型范围作用域” 这一概念有两个不同的关键字,它们分别是static和class。这两个关键字确实都表达了这个意思,但是在其他一些语言,包括Objective-C中,我们并不会特别地区分类变量/类方法和静态变量/静态函数。但是在Swift中,这两个关键字却是不能用混的。 在非class的类型上下文中,我们统一使用static来描述类型作用域。这包括在enum和struct

程序猿 4035

OC和Swift中的static

OC: static关键字表示静态,能够放在局部变量和全局变量前面: 限定作用域:对于静态全局变量来说,针对某一源文件的以static声明的文件级变量与函数的作用域只限于文件内(只在文件内可见),也即“内部连接”,因而可以用来限定变量的作用域; 标明生存周期:对于静态局部变量来说,在函数内以static声明的变量虽然与自动局部变量的作用域相同(即作用域都只限于函数内),但存储空间是以静态...

weixin_34203832的博客 192

static、class关键字

// // ViewController.swift // static_class import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // static 可以在类、结构体、或者枚举中使用,...

西瓜的博客 407

Swift开发必备技巧:static和class的使用

Swift中表示 “类型范围作用域” 这一概念有两个不同的关键字,它们分别是static和class。这两个关键字确实都表达了这个意思,但是在其他一些语言,包括Objective-C中,我们并不会特别地区分类变量/类方法和静态变量/静态函数。但是在Swift中,这两个关键字却是不能用混的。 在非class的类型上下文中,我们统一使用static来描述类型作用域。这包括在enum和struct中表

kaitoulee 451

Swift - class与staitc关键字的区别与使用(类方法、静态方法)

一、static 关键字 1、类Class的静态属性,静态方法也可以使用static关键字 class Acount { var amount : Double = 0.0 var owner : String = "" static var interestRate : Double = 0.668 ...

weixin_30454481的博客 201

Swift - static和class的使用

Swift中表示 “类型范围作用域” 这一概念有两个不同的关键字,它们分别是static和class。这两个关键字确实都表达了这个意思,但是在其他一些语言,包括Objective-C中,我们并不会特别地区分类变量/类方法和静态变量/静态函数。但是在Swift中,这两个关键字却是不能用混的。 static关键字 在非class的类型上下文中,我们统一使用static来描述类型作用域。这包括...

weixin_34138139的博客 139

Swift-----static、class定义类方法

(1)class只能用于类,static既可以用于类,还可以用于结构体、枚举 (2)class修饰的方法可以被继承,static修饰的方法不能够被继承 (3)类方法和实例方法的方法名可以相同 class Teacher { static func a() { } class func b() { } ...

weixin_30951743的博客 278
上一篇: 拆析系列_使用CATransform3D实现翻页效果
下一篇: <Learning SQL> O'REILLY_Chap. 1_背景知识
CaoYuan_CIKU
博客等级 码龄11年 40粉丝 58原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值