美文网首页
Swift初探

Swift初探

作者: Mr丶炎 | 来源:发表于2016-08-16 20:40 被阅读11次

    1.自定义打印语句
    2.代码书写

    • 自定义打印语句
      为什么要自定义打印语句呢?因为Swift太简单,连打印信息都只有一句话,一点提示都没有,根本找不到这个打印是从哪里来的,所有我们需要自定义打印语句,比较一下


      打印png

      可以看到自定义的打印语句可以看到很多信息

    而且在实际开发中,我们还应该做到当程序在debug环境下打印,在release环境下不打印,这才是自定义打印的本质所在。首先需要配置相关信息

    配置.png

    Swift中没有宏定义, 在Swift中有全局函数的概念,就是在任意位置让一个函数写在大{}外面,那么在整个工程中的任意地方的都可以调用该函数。所有我们应该将打印语句写成全局函数,而且最好写在AppDelegate中

    func LXYLog<T>(message : T, file : String = __FILE__, funcName : String = __FUNCTION__, lineNum : Int = __LINE__) {
        
        #if DEBUG
        
        let fileName = (file as NSString).lastPathComponent
        
        print("\(fileName):[\(funcName)](\(lineNum))-\(message)")
        
        #endif
        
    }
    
    
    • Swift书写
      为方便查看,使代码更美观一般都可以这样抽取,将相似功能代码放一块
    import UIKit
    
    class ViewController: UIViewController {
    
        lazy var tableView : UITableView = UITableView()
        
        override func viewDidLoad() {
            
            super.viewDidLoad()
            view.addSubview(tableView)
            
            setupUI()
    
        }
    }
    
    // MARK:- 设置UI相关
    extension ViewController {
        func setupUI() {
            tableView.frame = view.bounds
            tableView.dataSource = self
            tableView.delegate = self;
        }
    }
    
    // MARK:- 数据源和代理方法
    extension ViewController : UITableViewDataSource, UITableViewDelegate {
        
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 20;
        }
        
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cellId = "cellID"
            var cell = tableView.dequeueReusableCellWithIdentifier(cellId)
            if cell == nil {
                cell = UITableViewCell(style: .Default, reuseIdentifier: cellId)
            }
            
            cell?.textLabel?.text = "测试数据\(indexPath.row)";
            
            return cell!
        }
        
        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            print("点击了:\(indexPath.row)")
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Swift初探

          本文链接:https://www.haomeiwen.com/subject/bxnpsttx.html