Chaosky's Notes

Swift Tips

更新日志

  • 更新日期:2016-07-08

1. Swift 命令行程序接收用户输入

1
2
3
4
5
6
// 标准输入设备
let stdin = NSFileHandle.fileHandleWithStandardInput()
let inputData = keyboard.availableData
var inputStr = NSString(data: inputData, encoding: NSUTF8StringEncoding)
// 处理换行符
inputStr = inputStr?.stringByReplacingOccurrencesOfString("\n", withString: "")

2. 获取变量内存地址

unsafeAddressOf(_:)

返回类对象的指针,类型为UnsafePointer

函数原型
func unsafeAddressOf(_ object: AnyObject) -> UnsafePointer

示例代码

1
2
3
var str = "Hello, playground"
print(unsafeAddressOf(str))
// 0x00007f859a404ca0

func withUnsafePointer(: inout T, : @noescape (UnsafePointer) throws -> Result)
Invokes body with an UnsafePointer to arg and returns the result. Useful for calling Objective-C APIs that take “in/out” parameters (and default-constructible “out” parameters) by pointer.

函数原型
func withUnsafePointer( arg: inout T, body: @noescape (UnsafePointer) throws -> Result) rethrows -> Result

示例代码

1
2
3
4
5
6
struct Point {
var x: CGFloat, y: CGFloat
}
var point = Point(x: 10, y: 10)
print(withUnsafePointer(&point) {UnsafePointer<Point>($0)})
// 0x0000000115e3f8d8

Quick Swift Tips and Tricks

Swift Quick Tips

天下大事,必作于细!