如何利用 Swift 的語言特性來處理例外?使用 Optional 是常見的做法。如果成功就返回 value,失敗則返回 nil
,這種模式常用於簡單的狀況。然而,面對複雜的情況,例如網路請求,若只簡單返回 nil
,調用者並無法得知是 404,抑或 500。為了解決這個問題,我們必須緊緊抱住[錯誤/例外處理][wiki-exception-handling]的大腿。
(撰於 2017-04-10,基於 Swift 3.1)
#!/usr/bin/env Rscript | |
# | |
# ----- For NTU Forestry 3049 Course Only ----- | |
# | |
# Generate SpatialPointDataFrame based on dataset in Xitou | |
# | |
# This Gist: https://git.io/v6ozP | |
# | |
# Mail: b01605002@ntu.edu.tw | |
# Author: Weihang Lo |
opt_in_rules: | |
- closure_end_indentation | |
- closure_spacing | |
- empty_count | |
- force_unwrapping | |
- missing_docs | |
- operator_usage_whitespace | |
- private_outlet | |
- redundant_nil_coalescing | |
- overridden_super_call |
const blobURL = URL.createObjectURL(new Blob([ '(', | |
function () { | |
function fibonacci () {} | |
onmessage = function (ev) { | |
const result = processData(ev.data) | |
postMessage(result) | |
} | |
}.toString(), | |
/** | |
* GET request with a cancelable token | |
* @param {string} url - url to request | |
* @param {objecg} token - an object with a `cancel` function property. | |
* @return {Promise} | |
*/ | |
export function cancellableGet (url, token) { | |
const xhr = new XMLHttpRequest() | |
return new Promise(function (resolve, reject) { | |
token.cancel = function () { |
/** | |
* Get real element offset with an offsetParent referencing element | |
* | |
* `getBoundingClientRect` return values is not correct under CSS multi-column | |
* layout, so we recursively get `offsetLeft`/`offsetTop` instead. | |
* @param {HTMLElement} el - element of interest | |
* @param {HTMLElement} stopEl - one of the offsetParent as a reference | |
* @return {object} object wth top and left offset | |
*/ | |
export function getClientOffset (el, stopEl) { |
/** | |
* Calculate the rendered rect of img content (useful with object-fit: contain) | |
* @param {HTMLImageElement} img | |
* @return {object} rect of the object (the coordinate origin is top-left). | |
*/ | |
export function getRenderedRect (img) { | |
const style = window.getComputedStyle(img) | |
const pos = style.getPropertyValue('object-position').split(' ') | |
const contains = style.getPropertyValue('object-fit') === 'contain' |