2015年11月26日 星期四

Swift Optionals

在swift中使用Optional來處理值缺失的狀況,如果看見一個variable是Optional類型,只有兩種可能,要嘛有值,要嘛就是nil。

宣告方式

var coffee:String?

等於下面這種宣告方式

var coffee: Optional<String>

由此可知 ? 其實是syntactic sugar。

看看Optional的原始宣告

public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
    case None
    case Some(Wrapped)
    /// Construct a `nil` instance.
    public init()
    /// Construct a non-`nil` instance that stores `some`.
    public init(_ some: Wrapped)
    /// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
    @warn_unused_result
    public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
    /// Returns `nil` if `self` is nil, `f(self!)` otherwise.
    @warn_unused_result
    public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
    /// Create an instance initialized with `nil`.
    public init(nilLiteral: ())
}

如果沒有賦值的話,Optional的預設值是nil。在Objective-C中,nil是一個0指標,在swift中nil是一個確定的值,任何Optioanl都可以設為nil。關於瞭解空值,可以參考悟空

其他關於Optional chaining以及一些更深度的剖析,可以參考喵神的文章或是玉令天下的Blog

另外有一種情況是如果Optional呼叫的function需要傳入Optional本身,像

class ViewController: UIViewController {

    let finishedMessage = "Network call has finished"
    let messageLabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        someNetworkCall { [weak self] in
            self?.finished(self?.finishedMessage)
        }
    }

    func finished(message: String) {
        messageLabel.text = message
    }
}

這一段是編譯不過的,因為self?.finishedMessage是Optional chaining,而Optional chaining回傳的一定是Optional值。那麼應該怎麼解呢?

可以直接使用!,因為當self?為nil時不會繼續呼叫function,所以一旦呼叫了function就代表有值。

someNetworkCall { [weak self] in
            self?.finished(self!.finishedMessage)
}

詳情可以參考http://blog.xebia.com/swift-optional-chaining-and-method-argument-evaluation/

2015年11月4日 星期三

隱藏無內容的Self Sizing Cell

基本上看完优化UITableViewCell高度计算的那些事就可以大概瞭解從iOS7以後計算TableViewCell高度需要注意的事。

假設cell裡只有一個addressLabel,而且我們使用iOS8的self sizing,想讓無內容的cell高度變為0,也就是不顯示,可以把top跟bottom constraint的constant設為0。先把xib或storyboard中上下的constraint拉出IBOutlet到 .m 檔中,在cellForRowAtIndexPath的時候根據內容是否為空決定constant大小。

Constraint

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"ListTableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
    if (cell.addressLabel.text.length == 0) {
        cell.addressLabelTopConstraint.constant = 0;
        cell.addressLabelBottomConstraint.constant = 0;
    }
    else {
        cell.addressLabelTopConstraint.constant = 15;
        cell.addressLabelBottomConstraint.constant = 15;
    }
    [cell layoutIfNeeded];
    return cell;
}

addressLabel如果沒有內容,因為Label約束與上下邊緣一致 (constant為0),所以Label高度會被自動計算為0,且不會佔任何空間。