Swift开发RXSwift

Swift代码规范 2022-02-24 周四

2022-03-27  本文已影响0人  勇往直前888

语言规约

命名规范

//Swift 2.3
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

//Swift 3.0,cellForRowAtIndexPath简化成cellForRowAt。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
main.swift:10:5: error: 'test' is inaccessible due to 'internal' protection level
str.test()
^
<unknown>:0: note: 'test' declared here
<unknown>:0: note: 'test' declared here

代码组织

lazy var textLabel : UILabel = {
    let label = UILabel()
    label.font = UIFont.aly_f10
    label.textColor = UIColor.aly_ct_2
    label.textAlignment = .center
    label.text = "添加"
    self.contentView.addSubview(label)

    return label
}()

最佳实践

消除警告

@discardableResult
func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
    return SessionManager.default.request(urlRequest)
}

避免严重的崩溃

//guard let适合后面有大量代码依赖foo有值
guard let _foo = foo else {
    return
}

print(_foo)

//if let比较灵活
if let _foo = foo {
    //do something
}

//??更加灵活,但是一行代码使用过多??可能有性能问题。
print(foo?? "hello world")

避免内存泄露

let cell = ALYCommonCellObject.Builder()
    .title(title: "使用许可协议", color: UIColor.aly_black)
    .selectionAction(select: { [unowned self] (cell) in
        self?.utlogCounter("Setting", withMonitorPoint: "TermOfService")
    })
    .build()

合理选择数据类型

enum ALYVote : String {
    case approve = "approve"
    case clean   = "clean"
    case oppose  = "oppose"
}
let foo : Decimal = 10.12373223423
let bar : Decimal = 1.23423432432432

print(foo+bar) //11.3579665585543176192
print(foo-bar) //11.3579665585543176192
print(foo*bar) //12.4950578137552000654026872358296354816

合理选择修饰符

使用尾随闭包

//最复杂版本
let fullGreetings = guestList.map({(person: String) -> String in return "Hello, \(person)!"})

//最简单版本
let fullGreetings = guestList.map{ "Hello, \($0)!" }

使用Swift的新方式

class ALYXXX {
    static let sharedInstance = ALYXXX()
    private override init() {}
}
lazy var textLabel : UILabel = {
    let label = UILabel()
    label.font = UIFont.aly_f10
    label.textColor = UIColor.aly_ct_2
    label.textAlignment = .center
    label.text = "添加"
    self.contentView.addSubview(label)

    return label
}()
self.groupList.forEach { (id, name) -> Void in
    vc.groupList[id] = name
}
if exists(filename) {
    let file = open(filename, O_READ)

    defer close(file)

    while let line = try file.readline() {
        //
    }
}

优秀的Swift开发资源

Swift与Objective-C混编

//#define NW_NETWOEK_STATUS_NOTIFY @"TBNetworkStatusChangeNotify"
extern NSString* const NW_NETWOEK_STATUS_NOTIFY;
//typedef enum {
typedef NS_ENUM(NSUInteger, NetworkStatus) {
    NotReachable = 0,
    ReachableViaWiFi,
    ReachableVia2G,
    ReachableVia3G,
    ReachableVia4G
};
//} NetworkStatus;
//返回id,在Swift就必须要转型了。
//+ (id)sharedInstantce;
//(TBLoginCenter.sharedInstantce() as? LoginProtocol)

//使用instanceType符合规范
+ (instanceType)sharedInstantce;
- (__nullable id)itemWithName:(NSString * __nonnull)name;

//NS_ASSUME_NONNULL_BEGIN和NS_ASSUME_NONNULL_END将中间的代码都加上nonull,
//只需要对nullable的属性和参数单独声明就好了。
//iOS SDK惯用这种方法。可以多跳进去看看。
NS_ASSUME_NONNULL_BEGIN
@interface Foo : NSObject
@property (nonatomic, copy, nullable) NSString *bar1;
@property (nonatomic, copy) NSArray *bar2;
@end
NS_ASSUME_NONNULL_END

显著的坑

//可能会出现编译问题
open lazy var promptTitleLabel : UILabel = {
    let label = UILabel()

    return label
}()
protocol MyClassDelegate: class {
    func method()
}

class MyClass {
    weak var delegate: MyClassDelegate?
}

class ViewController: UIViewController, MyClassDelegate {
    // ...
    var someInstance: MyClass!

    override func viewDidLoad() {
        super.viewDidLoad()

        someInstance = MyClass()
        someInstance.delegate = self
    }

    //...
}
上一篇下一篇

猜你喜欢

热点阅读