repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Yummypets/YPImagePicker
|
Source/Pages/Video/YPVideoCaptureHelper.swift
|
1
|
11787
|
//
// YPVideoHelper.swift
// YPImagePicker
//
// Created by Sacha DSO on 27/01/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import AVFoundation
import CoreMotion
/// Abstracts Low Level AVFoudation details.
class YPVideoCaptureHelper: NSObject {
public var isRecording: Bool {
return videoOutput.isRecording
}
public var didCaptureVideo: ((URL) -> Void)?
public var videoRecordingProgress: ((Float, TimeInterval) -> Void)?
private let session = AVCaptureSession()
private var timer = Timer()
private var dateVideoStarted = Date()
private let sessionQueue = DispatchQueue(label: "YPVideoCaptureHelperQueue")
private var videoInput: AVCaptureDeviceInput?
private var videoOutput = AVCaptureMovieFileOutput()
private var videoRecordingTimeLimit: TimeInterval = 0
private var isCaptureSessionSetup: Bool = false
private var isPreviewSetup = false
private var previewView: UIView!
private var motionManager = CMMotionManager()
private var initVideoZoomFactor: CGFloat = 1.0
// MARK: - Init
public func start(previewView: UIView, withVideoRecordingLimit: TimeInterval, completion: @escaping () -> Void) {
self.previewView = previewView
self.videoRecordingTimeLimit = withVideoRecordingLimit
sessionQueue.async { [weak self] in
guard let strongSelf = self else {
return
}
if !strongSelf.isCaptureSessionSetup {
strongSelf.setupCaptureSession()
}
strongSelf.startCamera(completion: {
completion()
})
}
}
// MARK: - Start Camera
public func startCamera(completion: @escaping (() -> Void)) {
guard !session.isRunning else {
print("Session is already running. Returning.")
return
}
sessionQueue.async { [weak self] in
// Re-apply session preset
self?.session.sessionPreset = .photo
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch status {
case .notDetermined, .restricted, .denied:
self?.session.stopRunning()
case .authorized:
self?.session.startRunning()
completion()
self?.tryToSetupPreview()
@unknown default:
ypLog("unknown default reached. Check code.")
}
}
}
// MARK: - Flip Camera
public func flipCamera(completion: @escaping () -> Void) {
sessionQueue.async { [weak self] in
guard let strongSelf = self else {
return
}
strongSelf.session.beginConfiguration()
strongSelf.session.resetInputs()
if let videoInput = strongSelf.videoInput {
strongSelf.videoInput = flippedDeviceInputForInput(videoInput)
}
if let videoInput = strongSelf.videoInput {
if strongSelf.session.canAddInput(videoInput) {
strongSelf.session.addInput(videoInput)
}
}
// Re Add audio recording
if let audioDevice = AVCaptureDevice.audioCaptureDevice,
let audioInput = try? AVCaptureDeviceInput(device: audioDevice),
strongSelf.session.canAddInput(audioInput) {
strongSelf.session.addInput(audioInput)
}
strongSelf.session.commitConfiguration()
DispatchQueue.main.async {
completion()
}
}
}
// MARK: - Focus
public func focus(onPoint point: CGPoint) {
if let device = videoInput?.device {
setFocusPointOnDevice(device: device, point: point)
}
}
// MARK: - Zoom
public func zoom(began: Bool, scale: CGFloat) {
guard let device = videoInput?.device else {
return
}
if began {
initVideoZoomFactor = device.videoZoomFactor
return
}
do {
try device.lockForConfiguration()
defer { device.unlockForConfiguration() }
var minAvailableVideoZoomFactor: CGFloat = 1.0
if #available(iOS 11.0, *) {
minAvailableVideoZoomFactor = device.minAvailableVideoZoomFactor
}
var maxAvailableVideoZoomFactor: CGFloat = device.activeFormat.videoMaxZoomFactor
if #available(iOS 11.0, *) {
maxAvailableVideoZoomFactor = device.maxAvailableVideoZoomFactor
}
maxAvailableVideoZoomFactor = min(maxAvailableVideoZoomFactor, YPConfig.maxCameraZoomFactor)
let desiredZoomFactor = initVideoZoomFactor * scale
device.videoZoomFactor = max(minAvailableVideoZoomFactor,
min(desiredZoomFactor, maxAvailableVideoZoomFactor))
} catch let error {
ypLog("Error: \(error)")
}
}
// MARK: - Stop Camera
public func stopCamera() {
guard session.isRunning else {
return
}
sessionQueue.async { [weak self] in
self?.session.stopRunning()
}
}
// MARK: - Torch
public func hasTorch() -> Bool {
return videoInput?.device.hasTorch ?? false
}
public func currentTorchMode() -> AVCaptureDevice.TorchMode {
guard let device = videoInput?.device else {
return .off
}
if !device.hasTorch {
return .off
}
return device.torchMode
}
public func toggleTorch() {
videoInput?.device.tryToggleTorch()
}
// MARK: - Recording
public func startRecording() {
let outputURL = YPVideoProcessor.makeVideoPathURL(temporaryFolder: true, fileName: "recordedVideoRAW")
checkOrientation { [weak self] orientation in
guard let strongSelf = self else {
return
}
if let connection = strongSelf.videoOutput.connection(with: .video) {
if let orientation = orientation, connection.isVideoOrientationSupported {
connection.videoOrientation = orientation
}
strongSelf.videoOutput.startRecording(to: outputURL, recordingDelegate: strongSelf)
}
}
}
public func stopRecording() {
videoOutput.stopRecording()
}
// Private
private func setupCaptureSession() {
session.beginConfiguration()
let cameraPosition: AVCaptureDevice.Position = YPConfig.usesFrontCamera ? .front : .back
let aDevice = AVCaptureDevice.deviceForPosition(cameraPosition)
if let d = aDevice {
videoInput = try? AVCaptureDeviceInput(device: d)
}
if let videoInput = videoInput {
if session.canAddInput(videoInput) {
session.addInput(videoInput)
}
// Add audio recording
if let audioDevice = AVCaptureDevice.audioCaptureDevice,
let audioInput = try? AVCaptureDeviceInput(device: audioDevice),
session.canAddInput(audioInput) {
session.addInput(audioInput)
}
let timeScale: Int32 = 30 // FPS
let maxDuration =
CMTimeMakeWithSeconds(self.videoRecordingTimeLimit, preferredTimescale: timeScale)
videoOutput.maxRecordedDuration = maxDuration
if let sizeLimit = YPConfig.video.recordingSizeLimit {
videoOutput.maxRecordedFileSize = sizeLimit
}
videoOutput.minFreeDiskSpaceLimit = YPConfig.video.minFreeDiskSpaceLimit
if YPConfig.video.fileType == .mp4,
YPConfig.video.recordingSizeLimit != nil {
videoOutput.movieFragmentInterval = .invalid // Allows audio for MP4s over 10 seconds.
}
if session.canAddOutput(videoOutput) {
session.addOutput(videoOutput)
}
session.sessionPreset = .high
}
session.commitConfiguration()
isCaptureSessionSetup = true
}
// MARK: - Recording Progress
@objc
func tick() {
let timeElapsed = Date().timeIntervalSince(dateVideoStarted)
var progress: Float
if let recordingSizeLimit = YPConfig.video.recordingSizeLimit {
progress = Float(videoOutput.recordedFileSize) / Float(recordingSizeLimit)
} else {
progress = Float(timeElapsed) / Float(videoRecordingTimeLimit)
}
// VideoOutput configuration is responsible for stopping the recording. Not here.
DispatchQueue.main.async {
self.videoRecordingProgress?(progress, timeElapsed)
}
}
// MARK: - Orientation
/// This enables to get the correct orientation even when the device is locked for orientation \o/
private func checkOrientation(completion: @escaping(_ orientation: AVCaptureVideoOrientation?) -> Void) {
motionManager.accelerometerUpdateInterval = 5
motionManager.startAccelerometerUpdates( to: OperationQueue() ) { [weak self] data, _ in
self?.motionManager.stopAccelerometerUpdates()
guard let data = data else {
completion(nil)
return
}
let orientation: AVCaptureVideoOrientation = abs(data.acceleration.y) < abs(data.acceleration.x)
? data.acceleration.x > 0 ? .landscapeLeft : .landscapeRight
: data.acceleration.y > 0 ? .portraitUpsideDown : .portrait
DispatchQueue.main.async {
completion(orientation)
}
}
}
// MARK: - Preview
func tryToSetupPreview() {
if !isPreviewSetup {
setupPreview()
isPreviewSetup = true
}
}
func setupPreview() {
let videoLayer = AVCaptureVideoPreviewLayer(session: session)
DispatchQueue.main.async {
videoLayer.frame = self.previewView.bounds
videoLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.previewView.layer.addSublayer(videoLayer)
}
}
}
extension YPVideoCaptureHelper: AVCaptureFileOutputRecordingDelegate {
public func fileOutput(_ captureOutput: AVCaptureFileOutput,
didStartRecordingTo fileURL: URL,
from connections: [AVCaptureConnection]) {
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(tick),
userInfo: nil,
repeats: true)
dateVideoStarted = Date()
}
public func fileOutput(_ captureOutput: AVCaptureFileOutput,
didFinishRecordingTo outputFileURL: URL,
from connections: [AVCaptureConnection],
error: Error?) {
if let error = error {
ypLog("Error: \(error)")
}
if YPConfig.onlySquareImagesFromCamera {
YPVideoProcessor.cropToSquare(filePath: outputFileURL) { [weak self] url in
guard let _self = self, let u = url else { return }
_self.didCaptureVideo?(u)
}
} else {
self.didCaptureVideo?(outputFileURL)
}
timer.invalidate()
}
}
|
mit
|
43ebd5cc779e18f34b7020e45872b8b8
| 33.766962 | 117 | 0.584846 | 5.60971 | false | false | false | false |
isair/ManualLayout
|
ManualLayoutTests/UIScrollViewManualLayoutTests.swift
|
1
|
4000
|
//
// UIScrollViewManualLayoutTests.swift
// ManualLayout
//
// Created by Baris Sencan on 06/03/15.
// Copyright (c) 2015 Baris Sencan. All rights reserved.
//
import UIKit
import XCTest
import ManualLayout
internal final class UIScrollViewManualLayoutTests: XCTestCase {
let defaultContentSize = CGSize(width: 20, height: 20)
let defaultContentOffset = CGPoint(x: 10, y: 10)
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
override func setUp() {
scrollView.contentSize = defaultContentSize
scrollView.contentOffset = defaultContentOffset
}
func testContentWidth() {
XCTAssertEqual(
scrollView.contentWidth,
scrollView.contentSize.width,
"contentWidth should be equal to contentSize.width")
scrollView.contentWidth = 30
XCTAssertEqual(
scrollView.contentSize,
CGSize(width: 30, height: defaultContentSize.height),
"Setting contentWidth should modify contentSize correctly")
}
func testContentHeight() {
XCTAssertEqual(
scrollView.contentHeight,
scrollView.contentSize.height,
"contentHeight should be equal to contentSize.height")
scrollView.contentHeight = 30
XCTAssertEqual(
scrollView.contentSize,
CGSize(width: defaultContentSize.width, height: 30),
"Setting contentHeight should modify contentSize correctly")
}
func testContentTop() {
XCTAssert(
scrollView.contentTop == 0,
"contentTop should be equal to 0")
}
func testContentLeft() {
XCTAssert(
scrollView.contentLeft == 0,
"contentLeft should be equal to 0")
}
func testContentBottom() {
XCTAssertEqual(
scrollView.contentBottom,
scrollView.contentSize.height,
"contentBottom should be equal to contentSize.height")
scrollView.contentBottom = 30
XCTAssertEqual(
scrollView.contentSize,
CGSize(width: defaultContentSize.width, height: 30),
"Setting contentBottom should modify contentSize correctly")
}
func testContentRight() {
XCTAssertEqual(
scrollView.contentRight,
scrollView.contentSize.width,
"contentRight should be equal to contentSize.width")
scrollView.contentRight = 30
XCTAssertEqual(
scrollView.contentSize,
CGSize(width: 30, height: defaultContentSize.height),
"Setting contentRight should modify contentSize correctly")
}
func testViewportTop() {
XCTAssertEqual(
scrollView.viewportTop,
scrollView.contentOffset.y,
"viewportTop should be equal to contentOffset.y")
scrollView.viewportTop = 0
XCTAssertEqual(
scrollView.contentOffset,
CGPoint(x: defaultContentOffset.x, y: 0),
"Setting viewportTop should modify contentOffset correctly")
}
func testViewportLeft() {
XCTAssertEqual(
scrollView.viewportLeft,
scrollView.contentOffset.x,
"viewportLeft should be equal to contentOffset.x")
scrollView.viewportLeft = 0
XCTAssertEqual(
scrollView.contentOffset,
CGPoint(x: 0, y: defaultContentOffset.y),
"Setting viewportLeft should modify contentOffset correctly")
}
func testViewportBottom() {
XCTAssertEqual(
scrollView.viewportBottom,
scrollView.contentOffset.y + scrollView.frame.size.height,
"viewportBottom should be equal to contentOffset.y + height")
scrollView.viewportBottom = 10
XCTAssertEqual(
scrollView.contentOffset,
CGPoint(x: defaultContentOffset.x, y: 0),
"Setting viewportBottom should modify contentOffset correctly")
}
func testViewportRight() {
XCTAssertEqual(
scrollView.viewportRight,
scrollView.contentOffset.x + scrollView.frame.size.width,
"viewportRight should be equal to contentOffset.x + width")
scrollView.viewportRight = 10
XCTAssertEqual(
scrollView.contentOffset,
CGPoint(x: 0, y: defaultContentOffset.y),
"Setting viewportRight should modify contentOffset correctly")
}
}
|
mit
|
6e7ea05f121e1713c3a711a965747197
| 29.776923 | 81 | 0.71325 | 4.907975 | false | true | false | false |
jonnguy/HSTracker
|
HSTracker/UIs/Battlegrounds/BattlegroundsOverlayView.swift
|
1
|
3294
|
//
// BattlegroundsOverlayView.swift
// HSTracker
//
// Created by Martin BONNIN on 30/11/2019.
// Copyright © 2019 HearthSim LLC. All rights reserved.
//
import Foundation
import kotlin_hslog
class BattlegroundsOverlayView: NSView {
var heroes: [DeckEntry.Hero]?
var currentIndex = -1
init() {
super.init(frame: NSRect.zero)
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
//let backgroundColor: NSColor = NSColor(red: 0x48/255.0, green: 0x7E/255.0, blue: 0xAA/255.0, alpha: 0.3)
let backgroundColor = NSColor.clear
backgroundColor.set()
dirtyRect.fill()
}
private lazy var trackingArea: NSTrackingArea = NSTrackingArea(rect: NSRect.zero,
options: [.inVisibleRect, .activeAlways, .mouseEnteredAndExited, .mouseMoved],
owner: self,
userInfo: nil)
override func updateTrackingAreas() {
super.updateTrackingAreas()
if !self.trackingAreas.contains(trackingArea) {
self.addTrackingArea(trackingArea)
}
}
func displayHero(at: Int) {
// swiftlint:disable force_cast
let windowManager = (NSApplication.shared.delegate as! AppDelegate).coreManager.game.windowManager
// swiftlint:enable force_cast
// var minions = [BattlegroundsMinion]()
// minions.append(BattlegroundsMinion(CardId: "AT_005", attack: Int32(at), health: Int32(at), poisonous: false, divineShield: true))
// minions.append(BattlegroundsMinion(CardId: "AT_006", attack: Int32(at), health: Int32(at), poisonous: true, divineShield: false))
//
// let debugBoard = BattlegroundsBoard(currentTurn: 10, opponentHero: kotlin_hslog.Entity(), turn: 4, minions: minions)
// windowManager.battlegroundsDetailsWindow.setBoard(board: debugBoard)
//
// windowManager.show(controller: windowManager.battlegroundsDetailsWindow, show: true,
// frame: SizeHelper.battlegroundsDetailsFrame(), overlay: true)
if let hero = heroes?.first(where: {$0.board.leaderboardPlace - 1 == at}) {
windowManager.battlegroundsDetailsWindow.setBoard(board: hero.board)
windowManager.show(controller: windowManager.battlegroundsDetailsWindow, show: true,
frame: SizeHelper.battlegroundsDetailsFrame(), overlay: true)
} else {
windowManager.show(controller: windowManager.battlegroundsDetailsWindow, show: false)
}
}
override func mouseMoved(with event: NSEvent) {
let index = 7 - Int(CGFloat(event.locationInWindow.y / (self.frame.height/8)))
if index != currentIndex {
displayHero(at: index)
currentIndex = index
}
}
override func mouseEntered(with event: NSEvent) {
}
override func mouseExited(with event: NSEvent) {
displayHero(at: -1)
}
func setHeroes(heroes: [DeckEntry.Hero]) {
self.heroes = heroes
}
}
|
mit
|
a1c64befb6cc4a351b2adc1d20895359
| 34.793478 | 145 | 0.627999 | 4.271077 | false | false | false | false |
qlongming/shppingCat
|
shoppingCart-master/shoppingCart/Classes/Library/SnapKit/Debugging.swift
|
14
|
6696
|
//
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
/**
Used to allow adding a snp_label to a View for debugging purposes
*/
public extension View {
public var snp_label: String? {
get {
return objc_getAssociatedObject(self, &labelKey) as? String
}
set {
objc_setAssociatedObject(self, &labelKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
}
/**
Used to allow adding a snp_label to a LayoutConstraint for debugging purposes
*/
public extension LayoutConstraint {
public var snp_label: String? {
get {
return objc_getAssociatedObject(self, &labelKey) as? String
}
set {
objc_setAssociatedObject(self, &labelKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
override public var description: String {
var description = "<"
description += descriptionForObject(self)
description += " \(descriptionForObject(self.firstItem))"
if self.firstAttribute != .NotAnAttribute {
description += ".\(self.firstAttribute.snp_description)"
}
description += " \(self.relation.snp_description)"
if let secondItem: AnyObject = self.secondItem {
description += " \(descriptionForObject(secondItem))"
}
if self.secondAttribute != .NotAnAttribute {
description += ".\(self.secondAttribute.snp_description)"
}
if self.multiplier != 1.0 {
description += " * \(self.multiplier)"
}
if self.secondAttribute == .NotAnAttribute {
description += " \(self.constant)"
} else {
if self.constant > 0.0 {
description += " + \(self.constant)"
} else if self.constant < 0.0 {
description += " - \(CGFloat.abs(self.constant))"
}
}
if self.priority != 1000.0 {
description += " ^\(self.priority)"
}
description += ">"
return description
}
internal var snp_makerFile: String? {
return self.snp_constraint?.makerLocation.file
}
internal var snp_makerLine: UInt? {
return self.snp_constraint?.makerLocation.line
}
}
private var labelKey = ""
private func descriptionForObject(object: AnyObject) -> String {
let pointerDescription = NSString(format: "%p", ObjectIdentifier(object).uintValue)
var desc = ""
desc += object.dynamicType.description()
if let object = object as? View {
desc += ":\(object.snp_label ?? pointerDescription)"
} else if let object = object as? LayoutConstraint {
desc += ":\(object.snp_label ?? pointerDescription)"
} else {
desc += ":\(pointerDescription)"
}
if let object = object as? LayoutConstraint, let file = object.snp_makerFile, let line = object.snp_makerLine {
desc += "@\(file)#\(line)"
}
desc += ""
return desc
}
private extension NSLayoutRelation {
private var snp_description: String {
switch self {
case .Equal: return "=="
case .GreaterThanOrEqual: return ">="
case .LessThanOrEqual: return "<="
}
}
}
private extension NSLayoutAttribute {
private var snp_description: String {
#if os(iOS) || os(tvOS)
switch self {
case .NotAnAttribute: return "notAnAttribute"
case .Top: return "top"
case .Left: return "left"
case .Bottom: return "bottom"
case .Right: return "right"
case .Leading: return "leading"
case .Trailing: return "trailing"
case .Width: return "width"
case .Height: return "height"
case .CenterX: return "centerX"
case .CenterY: return "centerY"
case .Baseline: return "baseline"
case .FirstBaseline: return "firstBaseline"
case .TopMargin: return "topMargin"
case .LeftMargin: return "leftMargin"
case .BottomMargin: return "bottomMargin"
case .RightMargin: return "rightMargin"
case .LeadingMargin: return "leadingMargin"
case .TrailingMargin: return "trailingMargin"
case .CenterXWithinMargins: return "centerXWithinMargins"
case .CenterYWithinMargins: return "centerYWithinMargins"
}
#else
switch self {
case .NotAnAttribute: return "notAnAttribute"
case .Top: return "top"
case .Left: return "left"
case .Bottom: return "bottom"
case .Right: return "right"
case .Leading: return "leading"
case .Trailing: return "trailing"
case .Width: return "width"
case .Height: return "height"
case .CenterX: return "centerX"
case .CenterY: return "centerY"
case .Baseline: return "baseline"
default: return "default"
}
#endif
}
}
|
apache-2.0
|
4afd235a7e47dd25c7bc536a21c718cd
| 33.163265 | 119 | 0.574074 | 4.909091 | false | false | false | false |
dydyistc/DYWeibo
|
DYWeibo/Classes/Tools/FindEmoticon.swift
|
1
|
2478
|
//
// FindEmoticon.swift
// DYWeibo
//
// Created by Yi Deng on 13/05/2017.
// Copyright © 2017 TD. All rights reserved.
//
import UIKit
class FindEmoticon: NSObject {
// MARK:- 设计单例对象
static let sharedIntance : FindEmoticon = FindEmoticon()
// MARK:- 表情属性
fileprivate lazy var manager : EmoticonManager = EmoticonManager()
// 查找属性字符串的方法
func findAttrString(_ statusText : String?, font : UIFont) -> NSMutableAttributedString? {
// 0.如果statusText没有值,则直接返回nil
guard let statusText = statusText else {
return nil
}
// 1.创建匹配规则
let pattern = "\\[.*?\\]" // 匹配表情
// 2.创建正则表达式对象
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return nil
}
// 3.开始匹配
let results = regex.matches(in: statusText, options: [], range: NSRange(location: 0, length: statusText.characters.count))
// 4.获取结果
let attrMStr = NSMutableAttributedString(string: statusText)
for i in (0..<results.count).reversed() {
// 4.0.获取结果
let result = results[i]
// 4.1.获取chs
let chs = (statusText as NSString).substring(with: result.range)
// 4.2.根据chs,获取图片的路径
guard let pngPath = findPngPath(chs) else {
return nil
}
// 4.3.创建属性字符串
let attachment = NSTextAttachment()
attachment.image = UIImage(contentsOfFile: pngPath)
attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
let attrImageStr = NSAttributedString(attachment: attachment)
// 4.4.将属性字符串替换到来源的文字位置
attrMStr.replaceCharacters(in: result.range, with: attrImageStr)
}
// 返回结果
return attrMStr
}
fileprivate func findPngPath(_ chs : String) -> String? {
for package in manager.packages {
for emoticon in package.emoticons {
if emoticon.chs == chs {
return emoticon.pngPath
}
}
}
return nil
}
}
|
apache-2.0
|
abfb70e5049d06cfec3c16850accefbd
| 28.597403 | 130 | 0.53971 | 4.622718 | false | false | false | false |
lukesutton/hekk
|
Sources/Template.swift
|
1
|
1629
|
public struct Template<State> {
enum Mode {
case page(Document)
case partial(Node)
}
let initial: Mode
let process: (State, Node) -> Node?
public func step<S>(_ path: KeyPath<State, S>, _ fn: @escaping (S, Node) -> Node?) -> Template<State> {
return Template<State>(initial: initial) { state, node in
guard let update = self.process(state, node) else { return nil }
return fn(state[keyPath: path], update)
}
}
public func step(_ fn: @escaping (State, Node) -> Node?) -> Template<State> {
return Template<State>(initial: initial) { state, node in
guard let update = self.process(state, node) else { return nil }
return fn(state, update)
}
}
public func step(_ fn: @escaping (Node) -> Node?) -> Template<State> {
return Template<State>(initial: initial) { state, node in
guard let update = self.process(state, node) else { return nil }
return fn(update)
}
}
public func render(state: State, spec: HTMLSpec = .HTML5) throws -> String {
switch initial {
case let .page(doc):
guard let node = process(state, doc.root) else { throw EmptyTemplateError() }
return try Document(root: node).render(spec: spec)
case let .partial(node):
guard let node = process(state, node) else { throw EmptyTemplateError() }
return try node.render(spec: spec)
}
}
}
extension Template {
init(_ initial: Node) {
self.initial = .partial(initial)
self.process = { _, node in return node }
}
init(_ initial: Document) {
self.initial = .page(initial)
self.process = { _, node in return node }
}
}
|
mit
|
925ff42b46d687da5cbef81a0e708905
| 29.735849 | 105 | 0.630448 | 3.677201 | false | false | false | false |
infobip/mobile-messaging-sdk-ios
|
Classes/InteractiveNotifications/MessageAlert/InteractiveMessageAlert.swift
|
1
|
3838
|
//
// InteractiveMessageAlert.swift
// MobileMessaging
//
// Created by Andrey Kadochnikov on 23/04/2018.
//
import Foundation
import UserNotifications
@objc protocol InAppAlertDelegate {
func willDisplay(_ message: MM_MTMessage)
}
@objcMembers
public class MMInteractiveMessageAlertSettings: NSObject {
public static var errorPlaceholderText: String = "Sorry, couldn't load the image"
public static var tintColor = UIColor(red: 0, green: 122, blue: 255, alpha: 1)
public static var enabled: Bool = true
}
class InteractiveMessageAlertManager: NamedLogger {
static let sharedInstance = InteractiveMessageAlertManager()
var delegate: InAppAlertDelegate?
func cancelAllAlerts() {
AlertQueue.sharedInstace.cancelAllAlerts()
}
func showModalNotificationManually(forMessage message: MM_MTMessage) {
guard !message.isGeoSignalingMessage else {
logDebug("Geo signaling message cannot be displayed with in-app")
return
}
logDebug("Displaying modal in-app manually")
showModalNotification(forMessage: message, exclusively: false)
}
func showModalNotificationAutomatically(forMessage message: MM_MTMessage) {
guard let inAppStyle = message.inAppStyle, shouldShowInAppNotification(forMessage: message) else {
return
}
switch inAppStyle {
case .Banner:
break
case .Modal:
if (MobileMessaging.messageHandlingDelegate?.shouldShowModalInAppNotification?(for: message) ?? true) {
logDebug("Displaying modal in-app automatically")
showModalNotification(forMessage: message, exclusively: MobileMessaging.application.applicationState == .background)
} else {
logDebug("Modal notification for message: \(message.messageId) text: \(message.text.orNil) is disabled by MMMessageHandlingDelegate")
}
}
}
func showBannerNotificationIfNeeded(forMessage message: MM_MTMessage?, showBannerWithOptions: @escaping (UNNotificationPresentationOptions) -> Void) {
if let handlingSubservice = MobileMessaging.sharedInstance?.subservices.values.first(where: { $0.handlesInAppNotification(forMessage: message)}) {
handlingSubservice.showBannerNotificationIfNeeded(forMessage: message, showBannerWithOptions: showBannerWithOptions)
return
}
guard let message = message, let inAppStyle = message.inAppStyle, shouldShowInAppNotification(forMessage: message) else {
showBannerWithOptions([])
return
}
switch inAppStyle {
case .Banner:
showBannerWithOptions(InteractiveMessageAlertManager.presentationOptions(for: message))
case .Modal:
break
}
}
private func shouldShowInAppNotification(forMessage message: MM_MTMessage) -> Bool {
let enabled = MMInteractiveMessageAlertSettings.enabled
let notExpired = !message.isExpired
let noActionPerformed = (message.category != nil && message.appliedAction?.identifier == MMNotificationAction.DefaultActionId) || message.appliedAction == nil
let inAppRequired = message.inAppStyle != nil
return enabled && notExpired && inAppRequired && noActionPerformed && !message.isGeoSignalingMessage
}
private func showModalNotification(forMessage message: MM_MTMessage, exclusively: Bool) {
logDebug("Alert for message will be shown: \(message.messageId) text: \(message.text.orNil)")
if exclusively {
cancelAllAlerts()
}
AlertQueue.sharedInstace.enqueueAlert(message: message, text: message.text ?? "")
}
static func presentationOptions(for message: MM_MTMessage?) -> UNNotificationPresentationOptions {
let ret: UNNotificationPresentationOptions
if let msg = message, msg.inAppStyle == .Banner {
ret = UNNotificationPresentationOptions.make(with: MobileMessaging.sharedInstance?.userNotificationType ?? [])
} else {
ret = []
}
return ret
}
}
|
apache-2.0
|
3f0fe22c1889a8e14dba8370c39bb838
| 35.903846 | 160 | 0.746483 | 4.624096 | false | false | false | false |
rockgarden/swift_language
|
Playground/Swift Language Guide.playground/Pages/Basic Operators.xcplaygroundpage/Contents.swift
|
1
|
15866
|
//: [Previous](@previous)
import UIKit
/*:
# Basic Operators
An operator is a special symbol or phrase that you use to check, change, or combine values.
Swift supports most standard C operators and improves several capabilities to eliminate common coding errors. The assignment operator (=) does not return a value, to prevent it from being mistakenly used when the equal to operator (==) is intended. Arithmetic operators (+, -, *, /, % and so forth) detect and disallow value overflow, to avoid unexpected results when working with numbers that become larger or smaller than the allowed value range of the type that stores them. You can opt in to value overflow behavior by using Swift’s overflow operators.
Swift also provides two range operators (a..<b and a...b) not found in C, as a shortcut for expressing a range of values.
*/
/*:
# Terminology
Operators are unary, binary, or ternary:
- Unary operators operate on a single target (such as -a). Unary prefix operators appear immediately before their target (such as !b), and unary postfix operators appear immediately after their target (such as c!).
- Binary operators operate on two targets (such as 2 + 3) and are infix because they appear in between their two targets.
- Ternary operators operate on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (a ? b : c).
- The values that operators affect are operands. In the expression 1 + 2, the + symbol is a binary operator and its two operands are the values 1 and 2.
*/
/*:
# Assignment Operator
The assignment operator (a = b) initializes or updates the value of a with the value of b
*/
do {
let b = 10
var a = 5
a = b
/// If the right side of the assignment is a tuple with multiple values, its elements can be decomposed into multiple constants or variables at once:
let (x, y) = (1, 2)
// x is equal to 1, and y is equal to 2
/// Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value. The following statement is not valid:
//if x = y {}
/// This feature prevents the assignment operator (=) from being used by accident when the equal to operator (==) is actually intended. By making if x = y invalid, Swift helps you to avoid these kinds of errors in your code.
}
/*:
# Arithmetic Operators
Swift supports the four standard arithmetic operators for all number types:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
*/
do {
1 + 2 // equals 3
5 - 3 // equals 2
2 * 3 // equals 6
10.0 / 2.5 // equals 4.0
/// The addition operator is also supported for String concatenation:
"hello, " + "world" // equals "hello, world"
}
//: Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators do not allow values to overflow by default. You can opt in to value overflow behavior by using Swift’s overflow operators (such as a &+ b).
/*:
## Remainder Operator
The remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that is left over (known as the remainder).
- NOTE:
The remainder operator (%) is also known as a modulo operator in other languages. However, its behavior in Swift for negative numbers means that it is, strictly speaking, a remainder rather than a modulo operation.
*/
do {
9 % 4 // equals 1
-9 % 4 // equals -1
}
/*:
# Unary Minus Operator
The sign of a numeric value can be toggled using a prefixed -, known as the unary minus operator
The unary minus operator (-) is prepended directly before the value it operates on, without any white space.
*/
do {
let three = 3
let minusThree = -three // minusThree equals -3
let plusThree = -minusThree // plusThree equals 3, or "minus minus three"
}
/*:
# Unary Plus Operator
The unary plus operator (+) simply returns the value it operates on, without any change:
Although the unary plus operator doesn’t actually do anything, you can use it to provide symmetry in your code for positive numbers when also using the unary minus operator for negative numbers.
*/
do {
let minusSix = -6
let alsoMinusSix = +minusSix // alsoMinusSix equals -6
}
/*:
# Compound Assignment Operators
Like C, Swift provides compound assignment operators that combine assignment (=) with another operation. One example is the addition assignment operator (+=).
- NOTE:
The compound assignment operators do not return a value. For example, you cannot write let b = a += 2.
For a complete list of the compound assignment operators provided by the Swift standard library, see https://developer.apple.com/reference/swift/swift_standard_library_operators.
*/
do {
var a = 1
a += 2
}
/*:
# Comparison Operators
Swift supports all standard C comparison operators:
- Equal to (a == b)
- Not equal to (a != b)
- Greater than (a > b)
- Less than (a < b)
- Greater than or equal to (a >= b)
- Less than or equal to (a <= b)
- NOTE:
Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance. For more information, see Classes and Structures.
*/
do {
1 == 1
2 != 1
2 > 1
1 < 2
1 >= 1
2 <= 1
let name = "world"
if name == "world" {
print("hello, world")
} else {
print("I'm sorry \(name), but I don't recognize you")
}
}
/*:
## tuple comparison
You can also compare tuples that have the same number of values, as long as each of the values in the tuple can be compared. For example, both Int and String can be compared, which means tuples of the type (Int, String) can be compared. In contrast, Bool can’t be compared, which means tuples that contain a Boolean value can’t be compared. 您还可以比较具有相同数量值的元组,只要可以比较元组中的每个值即可。例如,可以比较Int和String,这意味着可以比较类型(Int,String)的元组。 相反,Bool无法比较,这意味着不能比较包含布尔值的元组。
Tuples are compared from left to right, one value at a time, until the comparison finds two values that aren’t equal. Those two values are compared, and the result of that comparison determines the overall result of the tuple comparison. If all the elements are equal, then the tuples themselves are equal. 元组从左到右进行比较,一次一个值,直到比较发现两个不相等的值。比较这两个值,比较结果确定元组比较的总体结果。如果所有元素都相等,那么元组本身是相等的。
- NOTE
The Swift standard library includes tuple comparison operators for tuples with fewer than seven elements. To compare tuples with seven or more elements, you must implement the comparison operators yourself. Swift标准库包括具有少于七个元素的元组的元组比较运算符。 要将元组与七个或更多元素进行比较,您必须自己实现比较运算符。
*/
do {
(1, "zebra") < (2, "apple") // true because 1 is less than 2; "zebra" and "apple" are not compared
(3, "apple") < (3, "bird") // true because 3 is equal to 3, and "apple" is less than "bird"
(4, "dog") == (4, "dog") // true because 4 is equal to 4, and "dog" is equal to "dog"
}
/*:
## Ternary Conditional Operator
The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2. It is a shortcut for evaluating one of two expressions based on whether question is true or false. If question is true, it evaluates answer1 and returns its value; otherwise, it evaluates answer2 and returns its value.
*/
do {
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
}
/*:
# Nil-Coalescing Operator
The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.
The nil-coalescing operator is shorthand for the code below:
a != nil ? a! : b
The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.
- NOTE:
If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.
*/
do {
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
}
/*:
# Range Operators
Swift includes two range operators, which are shortcuts for expressing a range of values.
## Closed Range Operator
The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.
*/
do {
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
}
/*:
## Half-Open Range Operator
The half-open range operator (a..<b) defines a range that runs from a to b, but does not include b. It is said to be half-open because it contains its first value, but not its final value. As with the closed range operator, the value of a must not be greater than b. If the value of a is equal to b, then the resulting range will be empty.
*/
do {
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("Person \(i + 1) is called \(names[i])")
}
}
/*:
# Logical Operators
Logical operators modify or combine the Boolean logic values true and false. Swift supports the three standard logical operators found in C-based languages:
- Logical NOT (!a)
- Logical AND (a && b)
- Logical OR (a || b)
## Logical NOT Operator
The logical NOT operator (!a) inverts a Boolean value so that true becomes false, and false becomes true.
The logical NOT operator is a prefix operator, and appears immediately before the value it operates on, without any white space. It can be read as “not a”.
*/
do {
let allowedEntry = false
if !allowedEntry {
print("ACCESS DENIED")
}
}
/*:
## Logical AND Operator
The logical AND operator (a && b) creates logical expressions where both values must be true for the overall expression to also be true.
If either value is false, the overall expression will also be false. In fact, if the first value is false, the second value won’t even be evaluated, because it can’t possibly make the overall expression equate to true. This is known as short-circuit evaluation.
*/
do {
let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
}
/*:
## LLogical OR Operator
The logical OR operator (a || b) is an infix operator made from two adjacent pipe characters. You use it to create logical expressions in which only one of the two values has to be true for the overall expression to be true.
Like the Logical AND operator above, the Logical OR operator uses short-circuit evaluation to consider its expressions. If the left side of a Logical OR expression is true, the right side is not evaluated, because it cannot change the outcome of the overall expression.
*/
do {
let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
}
/*:
## Combining Logical Operators
You can combine multiple logical operators to create longer compound expressions:
- NOTE:
The Swift logical operators && and || are left-associative, meaning that compound expressions with multiple logical operators evaluate the leftmost subexpression first.
*/
do {
let enteredDoorCode = true
let passedRetinaScan = false
let hasDoorKey = false
let knowsOverridePassword = true
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
}
/*:
## Explicit Parentheses
It is sometimes useful to include parentheses when they are not strictly needed, to make the intention of a complex expression easier to read. In the door access example above, it is useful to add parentheses around the first part of the compound expression to make its intent explicit.
*/
do {
let enteredDoorCode = true
let passedRetinaScan = false
let hasDoorKey = false
let knowsOverridePassword = true
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
print("Welcome!")
} else {
print("ACCESS DENIED")
}
}
/*: # Example
let hello = "Hola, qué tal"
var word = "world"
let (x, y) = (1, 2)
//: ## 运算符
var c1 = 19/4
var ww = 4.0/0.0
var fff = 0.0/0.0 //非数
var g = -5.2
var h = -3.1
//var mod = g%h //求余结果正负取决于被除数
var a111 = 5
//TODO: swift 实现自增
//var b111 = a111++ + 6 //先计算再自增
//var c111 = ++a111 + 6 //自增再计算
//: ## 溢出运算符 &+,&-,&*,&/,&%
var cmin = UInt8.min
//var f = cmin-1 //error
cmin = cmin &- 1 //下溢
//: ## 浮点数求余
var rem = 10%2
/*:
## 特征运算符
基于引用的对象比较
- 等价于 ( === )
- 不等价于 ( !== )
*/
do {
class T {}
let a = T()
var b = a
let c = T()
// ab指向的类型实例相同时c为ture
let bool1 = (a === b)
let bool2 = (c !== b)
}
/*:
## 字符串拼接
strings can be achieved by "sum" or by \()
*/
(hello + " " + word)
("\(hello) \(word)")
//: ### 字符串String插值
var apples = 10
var oranges = 4
("I have \(apples + oranges) fruits") //自动转型
//: 字符串NSString连接
var i = 200
var str = "Hello Swift"
var strN: NSString
strN = str as NSString
//TODO: String to NSString 转成Foundation
str = "\(str),\(i)"
strN.substring(with: NSRange(location: 0, length: 5)) //可用NSString的相关方法
//: ## 三目(元)运算符
let name = "uraimo"
var happyStr = ""
(1...4).forEach{ happyStr = ("Happy Birthday " + (($0 == 1) ? "dear \(name)":"to You"))}
happyStr
//var ab = a>b ? "a>b":"a<b"
/*:
Nil Coalescing Operator
- It's equivalent to (a ? b : c), but for optionals
- 空合并运算符 (a ?? b)对a进行空判断,若a有值就解封,否则返回b
- 表达式a必是可选类型 默认值b的类型必须要和a存储的类型保持一致
*/
var say:String?
var content = say ?? word
var optional: String? //Currently nil
// optional = "Some Value"
// Uncomment/comment this line and observe what values get printed below
var value = optional ?? "Value when `optional` is nil"
// above statement is equivalent to below
if optional != nil {
value = optional! //Unwrapped value
} else {
value = "Value when `optional` is nil"
}
//Range operators
//闭区间运算符 a...b
for index in 1...5 {
//It will iterate 5 times.
}
//半开区间运算符 a..<b
var array = [1,2,3]
for index in 1..<array.count{
//It will iterate (array.count - 1) times.
}
//枚举Enumerate array with index and value, C loop will be removed soon
for (index, value) in array.enumerated() {
("value \(value) at index \(index)")
}
var image = UIImage(named: "1")
//: ## Operator Overloading
// 运算符重载函数
func * (lhs: String, rhs: Int) -> String {
var result = lhs
for _ in 2...rhs {
result += lhs
}
return result
}
let u = "abc"
let v = u * 5
*/
//: [Next](@next)
|
mit
|
4c0631ab645dfc6e115edc35097c82c9
| 36.538653 | 557 | 0.694812 | 3.816684 | false | false | false | false |
Instagram/IGListKit
|
Examples/Examples-iOS/IGListKitExamples/ViewControllers/SupplementaryViewController.swift
|
1
|
1758
|
/*
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import IGListKit
import UIKit
final class SupplementaryViewController: UIViewController, ListAdapterDataSource {
lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self)
}()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
let feedItems = [
FeedItem(pk: 1, user: User(pk: 100, name: "Jesse", handle: "jesse_squires"), comments: ["You rock!", "Hmm you sure about that?"]),
FeedItem(pk: 2, user: User(pk: 101, name: "Ryan", handle: "_ryannystrom"), comments: ["lgtm", "lol", "Let's try it!"]),
FeedItem(pk: 3, user: User(pk: 102, name: "Ann", handle: "abaum"), comments: ["Good luck!"]),
FeedItem(pk: 4, user: User(pk: 103, name: "Phil", handle: "phil"), comments: ["yoooooooo", "What's the eta?"])
]
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
adapter.collectionView = collectionView
adapter.dataSource = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
// MARK: ListAdapterDataSource
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return feedItems
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
return FeedItemSectionController()
}
func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil }
}
|
mit
|
82aaa3b23d380ab6381cfdc2ac4b950e
| 34.877551 | 138 | 0.671217 | 4.395 | false | false | false | false |
csontosgabor/Twitter_Post
|
Twitter_Post/LocationManager.swift
|
1
|
4814
|
//
// LocationManager.swift
// Twitter_Post
//
// Created by Gabor Csontos on 12/18/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import CoreLocation
import MapKit
public typealias LocationManagerSuccess = (String?, CLLocation?) -> Void
public typealias LocationManagerFailure = (NSError) -> Void
public class LocationManager: NSObject, CLLocationManagerDelegate {
public enum Location: Int {
case City
case SubLocality
}
private let errorDomain = "com.zero.locationManager"
private var success: LocationManagerSuccess?
private var failure: LocationManagerFailure?
//Location Manager
private let locationManager = CLLocationManager()
private var location: Location = Location.City
public override init() { }
public func onSuccess(_ success: @escaping LocationManagerSuccess) -> Self {
self.success = success
return self
}
public func onFailure(_ failure: @escaping LocationManagerFailure) -> Self {
self.failure = failure
return self
}
public func getLocation(_ sybType: Location) -> Self {
_ = LocationAuthorizer { error in
if error == nil {
//set the locationType to City or SubLocality
self.location = sybType
self._getLocation()
} else {
if CLLocationManager.locationServicesEnabled() {
self.locationManager.requestWhenInUseAuthorization()
self._getLocation()
} else {
self.failure?(error!)
}
}
}
return self
}
func _getLocation() {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation()
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
if let location = locations.first {
self.locationManager.stopUpdatingLocation()
let geocoder = CLGeocoder()
let userlocation = location.coordinate
geocoder.reverseGeocodeLocation(CLLocation(latitude: userlocation.latitude,longitude: userlocation.longitude), completionHandler: {
placemarks, error in
if (error != nil) {
let error = errorWithKey("error.cant-get-location", domain: self.errorDomain)
self.failure?(error)
return
}
if placemarks!.count > 0 {
let placemark = CLPlacemark(placemark: placemarks![0] as CLPlacemark)
switch self.location {
case .City: self.success?(placemark.locality, location)
case .SubLocality: self.success?(placemark.subLocality, location)
}
} else {
let error = errorWithKey("error.cant-get-location", domain: self.errorDomain)
self.failure?(error)
}
})
} else {
let error = errorWithKey("error.cant-get-location", domain: self.errorDomain)
self.failure?(error)
}
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// self.locationManager.stopUpdatingLocation()
let error = errorWithKey("error.cant-get-location", domain: self.errorDomain)
self.failure?(error)
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .denied, .restricted, .notDetermined:
let error = errorWithKey("error.cant-get-location", domain: self.errorDomain)
self.failure?(error)
return
default:
break// self.locationManager.startUpdatingLocation()
}
}
}
//distance manager
internal func getDistance(_ currentLocation: CLLocation, placeLocation: CLLocation) -> String {
let distanceInMeters = placeLocation.distance(from: currentLocation)
let formatter = MKDistanceFormatter()
formatter.unitStyle = .abbreviated
let distanceString = formatter.string(fromDistance: distanceInMeters)
return distanceString
}
|
mit
|
7a5a3d9dbe0bab0dfcd2e7e2fcee6dab
| 29.27044 | 143 | 0.565759 | 5.978882 | false | false | false | false |
tokyovigilante/CesiumKit
|
CesiumKit/Renderer/DrawCommand.swift
|
1
|
6550
|
//
// DrawCommand.swift
// CesiumKit
//
// Created by Ryan Walklin on 15/06/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Metal
/**
* Represents a command to the renderer for drawing.
*
* @private
*/
class DrawCommand: Command {
/**
* The bounding volume of the geometry in world space. This is used for culling and frustum selection.
* <p>
* For best rendering performance, use the tightest possible bounding volume. Although
* <code>undefined</code> is allowed, always try to provide a bounding volume to
* allow the tightest possible near and far planes to be computed for the scene, and
* minimize the number of frustums needed.
* </p>
*
* @type {Object}
* @default undefined
*
* @see DrawCommand#debugShowBoundingVolume
*/
var boundingVolume: BoundingVolume? = nil
/**
* The oriented bounding box of the geometry in world space. If this is defined, it is used instead of
* {@link DrawCommand#boundingVolume} for plane intersection testing.
*
* @type {OrientedBoundingBox}
* @default undefined
*
* @see DrawCommand#debugShowBoundingVolume
*/
var orientedBoundingBox: OrientedBoundingBox? = nil
/**
* When <code>true</code>, the renderer frustum and horizon culls the command based on its {@link DrawCommand#boundingVolume}.
* If the command was already culled, set this to <code>false</code> for a performance improvement.
*
* @type {Boolean}
* @default true
*/
var cull: Bool
/**
* The transformation from the geometry in model space to world space.
* <p>
* When <code>undefined</code>, the geometry is assumed to be defined in world space.
* </p>
*
* @type {Matrix4}
* @default undefined
*/
var modelMatrix: Matrix4?
/**
* The type of geometry in the vertex array.
*
* @type {PrimitiveType}
* @default PrimitiveType.TRIANGLES
*/
var primitiveType: MTLPrimitiveType = .triangle
/**
* The vertex array.
*
* @type {VertexArray}
* @default undefined
*/
var vertexArray: VertexArray?
/**
* The number of vertices to draw in the vertex array.
*
* @type {Number}
* @default undefined
*/
var count: Int?
/**
* The offset to start drawing in the vertex array.
*
* @type {Number}
* @default 0
*/
var offset: Int = 0
/**
* An object with functions whose names match the uniforms in the shader program
* and return values to set those uniforms.
*
* @type {Object}
* @default undefined
*/
var uniformMap: UniformMap?
/**
* The render state.
*
* @type {RenderState}
* @default undefined
*/
var renderState: RenderState?
/**
* The render pipeline to apply.
*
* @type {RenderPipeline}
* @default undefined
*/
var pipeline: RenderPipeline? = nil
/**
* The pass when to render.
*
* @type {Pass}
* @default undefined
*/
var pass: Pass = .globe
/**
* Specifies if this command is only to be executed in the frustum closest
* to the eye containing the bounding volume. Defaults to <code>false</code>.
*
* @type {Boolean}
* @default false
*/
var executeInClosestFrustum: Bool = false
/**
* The object who created this command. This is useful for debugging command
* execution; it allows us to see who created a command when we only have a
* reference to the command, and can be used to selectively execute commands
* with {@link Scene#debugCommandFilter}.
*
* @type {Object}
* @default undefined
*
* @see Scene#debugCommandFilter
*/
var owner: AnyObject? = nil
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* <p>
* Draws the {@link DrawCommand#boundingVolume} for this command, assuming it is a sphere, when the command executes.
* </p>
*
* @type {Boolean}
* @default false
*
* @see DrawCommand#boundingVolume
*/
var debugShowBoundingVolume: Bool
/**
* Used to implement Scene.debugShowFrustums.
* @private
*/
var debugOverlappingFrustums: Int
/**
* @private
*/
//var oit = undefined;
var dirty: Bool = true
init(
boundingVolume: BoundingVolume? = nil,
orientedBoundingBox: OrientedBoundingBox? = nil,
cull: Bool = true,
modelMatrix: Matrix4? = nil,
primitiveType: MTLPrimitiveType = .triangle,
vertexArray: VertexArray? = nil,
count: Int? = nil,
offset: Int = 0,
uniformMap: UniformMap? = nil,
renderState: RenderState? = nil,
renderPipeline: RenderPipeline? = nil,
pass: Pass = .globe,
executeInClosestFrustum: Bool = false,
owner: AnyObject? = nil,
debugShowBoundingVolume: Bool = false,
debugOverlappingFrustums: Int = 0
) {
self.boundingVolume = boundingVolume
self.cull = cull
self.primitiveType = primitiveType
self.vertexArray = vertexArray
self.count = count
self.offset = offset
self.pipeline = renderPipeline
self.renderState = renderState
self.pass = pass
self.executeInClosestFrustum = executeInClosestFrustum
self.owner = owner
self.debugShowBoundingVolume = debugShowBoundingVolume
self.debugOverlappingFrustums = debugOverlappingFrustums
self.uniformMap = uniformMap
}
/**
* Executes the draw command.
*
* @param {Context} context The renderer context in which to draw.
* @param {RenderPass} [renderPass] The render pass this command is part of.
* @param {RenderState} [renderState] The render state that will override the render state of the command.
* @param {RenderPipeline} [renderPipeline] The render pipeline that will override the shader program of the command.
*/
func execute(_ context: Context, renderPass: RenderPass, frustumUniformBuffer: Buffer? = nil) {
context.draw(self, renderPass: renderPass, frustumUniformBuffer: frustumUniformBuffer)
}
deinit {
guard let provider = uniformMap?.uniformBufferProvider else {
return
}
provider.deallocationBlock?(provider)
}
}
|
apache-2.0
|
56c294b1d204a725f58878943a0d115f
| 27.354978 | 129 | 0.619542 | 4.352159 | false | false | false | false |
life4coding/DIFFQR
|
QRTarget/QRHacker.swift
|
1
|
8481
|
//
// QRHacker.swift
// QRTarget
//
// Created by kiwi on 2017/5/23.
// Copyright © 2017年 DIFF. All rights reserved.
//
import UIKit
import AVFoundation
import CoreImage
// scan from camera
// scan from photo library
//code string to QRCode
//can set functions
// can set animation
//can set completion(open with safari ? copy to copyboard?)
// uiimageview extension: to scan qrcode in image
//wait to do: set function button size dynamically
public class QRHackerViewController : UIViewController, AVCaptureMetadataOutputObjectsDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var session = AVCaptureSession.init()
public var didScanComplete:((_ result:String)->Void)?
public var didScanFiald:(()->Void)?
//view life cycle
override public func viewDidLoad() {
super.viewDidLoad()
requsetCameraPrivacy()
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setUpCancelScan()
}
//request privacy
func requsetCameraPrivacy(){
let cameraMediaType = AVMediaTypeVideo
let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(forMediaType: cameraMediaType)
switch cameraAuthorizationStatus {
// The client is authorized to access the hardware supporting a media type.
case .authorized:
_ = setUpScanFromCamera()
// The client is not authorized to access the hardware for the media type. The user cannot change
// the client's status, possibly due to active restrictions such as parental controls being in place.
case .restricted:
break //alertMessageAction("Camera Have Restricted", complete: nil)
// The user explicitly denied access to the hardware supporting a media type for the client.
case .denied:
//alertMessageAction("Camera Have Denied, Please Enable in System Settings", complete: nil)
break
// Indicates that the user has not yet made a choice regarding whether the client can access the hardware.
case .notDetermined:
// Prompting user for the permission to use the camera.
AVCaptureDevice.requestAccess(forMediaType: cameraMediaType) { [unowned self ] granted in
if granted {
//self.view.setNeedsDisplay()
DispatchQueue.main.async {
_ = self.setUpScanFromCamera()
}
} else {
print("Not granted access to \(cameraMediaType)")
}
}
// break
}
}
func setUpScanFromLibrary(){
}
func setUpCancelScan(){
//set tool view
let blurEffect = UIBlurEffect.init(style: .light)
let blurView = UIVisualEffectView.init(effect: blurEffect)
blurView.frame = CGRect.init(x: 0, y: self.view.bounds.size.height-150, width: self.view.bounds.size.width, height: 150)
self.view.addSubview(blurView)
//set choose from photos
let photoButton = UIButton.init(type: .custom)
photoButton.addTarget(self, action: #selector(openPhotoLibrary), for: .touchUpInside)
photoButton.setImage(UIImage.init(named: "photo"), for: .normal)
photoButton.bounds.size = CGSize.init(width: 50, height: 50)
photoButton.frame.origin = CGPoint.init(x: 20, y: blurView.bounds.height/2 - 25)
blurView.addSubview(photoButton)
//set cancel button
let cancelButton = UIButton.init(type: .custom)
cancelButton.setImage(UIImage.init(named: "back"), for: .normal)
cancelButton.bounds.size = CGSize.init(width: 50, height: 50)
cancelButton.frame.origin = CGPoint.init(x: blurView.bounds.width-70 , y: blurView.bounds.height/2 - 25)
cancelButton.addTarget(self, action: #selector(cancelScan), for: .touchUpInside)
blurView.addSubview(cancelButton)
}
func setUpScanFromCamera(){
let device = AVCaptureDevice.defaultDevice(withMediaType:AVMediaTypeVideo)
var input : AVCaptureDeviceInput?
do {
input = try AVCaptureDeviceInput.init(device: device)
}catch _ as NSError {
//
}
let output = AVCaptureMetadataOutput.init()
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
session.canSetSessionPreset(AVCaptureSessionPresetHigh)
session.addInput(input)
session.addOutput(output)
output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
let layer = AVCaptureVideoPreviewLayer.init(session: session)
layer?.videoGravity = AVLayerVideoGravityResizeAspectFill
layer?.frame = self.view.frame
self.view.layer.insertSublayer(layer!, at: 0)
session.startRunning()
}
func cancelScan(){
self.dismiss(animated: true, completion: nil)
}
func openPhotoLibrary(){
let controller = UIImagePickerController.init()
controller.sourceType = UIImagePickerControllerSourceType.photoLibrary
controller.delegate = self
self.present(controller, animated: true, completion: nil)
}
public func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if metadataObjects.count > 0{
let ob = metadataObjects.first as! AVMetadataMachineReadableCodeObject
self.dismiss(animated: true, completion: {
self.didScanComplete!(ob.stringValue)
})
}
}
//MARK: imagePicker delegate methohs
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
//
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage]
picker.dismiss(animated: true) {
let result = QRHacker.scanQRFromPhotos(image as! UIImage)
self.dismiss(animated: true, completion: {
self.didScanComplete!(result)
})
}
}
//MARK: generate and scan qr code with picture
//create qr code image from string
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
public class QRHacker:NSObject{
public static func creatQRCode(withString str:String) -> UIImage{
let data = str.data(using: String.Encoding.utf8,allowLossyConversion: false)
let filter = CIFilter.init(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("Q", forKey: "inputCorrectionLevel")
let qrImage = filter?.outputImage
return UIImage.init(ciImage: qrImage!)
}
//scan QR Image from a picture
public static func scanQRFromPhotos(_ image:UIImage) -> String{
let detector = CIDetector.init(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])
let results = detector?.features(in: CIImage.init(image: image)!)
if !(results?.isEmpty)!{
let result = results?.first as! CIQRCodeFeature
return result.messageString!
}else{
return "nothing"
}
}
}
//class AutoDetectImageView: UIImageView{
//
// var didScanComplete:((_ result:String)->Void)?
//
//
//
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// }
//
// func longPressTriggered(){
//
// let result = QRHacker.scanQRFromPhotos(self.image!)
// didScanComplete!(result)
//
// }
//
//}
|
bsd-2-clause
|
eb2c8e75e2236baf6bad240920a0fab1
| 28.957597 | 160 | 0.608516 | 5.31203 | false | false | false | false |
ahoppen/swift
|
test/SILGen/foreign_errors.swift
|
4
|
19545
|
// RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name foreign_errors -parse-as-library %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import errors
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors5test0yyKF : $@convention(thin) () -> @error Error
func test0() throws {
// Create a strong temporary holding nil before we perform any further parts of function emission.
// CHECK: [[ERR_TEMP0:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: inject_enum_addr [[ERR_TEMP0]] : $*Optional<NSError>, #Optional.none!enumelt
// CHECK: [[SELF:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// Create an unmanaged temporary, copy into it, and make a AutoreleasingUnsafeMutablePointer.
// CHECK: [[ERR_TEMP1:%.*]] = alloc_stack $@sil_unmanaged Optional<NSError>
// CHECK: [[T0:%.*]] = load_borrow [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = ref_to_unmanaged [[T0]]
// CHECK: store [[T1]] to [trivial] [[ERR_TEMP1]]
// CHECK: address_to_pointer [[ERR_TEMP1]]
// Call the method.
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{.*}}, [[SELF]])
// Writeback to the first temporary.
// CHECK: [[T0:%.*]] = load [trivial] [[ERR_TEMP1]]
// CHECK: [[T1:%.*]] = unmanaged_to_ref [[T0]]
// CHECK: [[T1_COPY:%.*]] = copy_value [[T1]]
// CHECK: assign [[T1_COPY]] to [[ERR_TEMP0]]
// Pull out the boolean value and compare it to zero.
// CHECK: [[BOOL_OR_INT:%.*]] = struct_extract [[RESULT]]
// CHECK: [[RAW_VALUE:%.*]] = struct_extract [[BOOL_OR_INT]]
// On some platforms RAW_VALUE will be compared against 0; on others it's
// already an i1 (bool) and those instructions will be skipped. Just do a
// looser check.
// CHECK: cond_br {{%.+}}, [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
try ErrorProne.fail()
// Normal path: fall out and return.
// CHECK: [[NORMAL_BB]]:
// CHECK: return
// Error path: fall out and rethrow.
// CHECK: [[ERROR_BB]]:
// CHECK: [[T0:%.*]] = load [take] [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = function_ref @$s10Foundation22_convertNSErrorToErrorys0E0_pSo0C0CSgF : $@convention(thin) (@guaranteed Optional<NSError>) -> @owned Error
// CHECK: [[T2:%.*]] = apply [[T1]]([[T0]])
// CHECK: "willThrow"([[T2]] : $Error)
// CHECK: throw [[T2]] : $Error
}
extension NSObject {
@objc func abort() throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil hidden [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE5abortyyKFTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: [[T0:%.*]] = function_ref @$sSo8NSObjectC14foreign_errorsE5abortyyKF : $@convention(method) (@guaranteed NSObject) -> @error Error
// CHECK: try_apply [[T0]](
// CHECK: bb1(
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, {{1|-1}}
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb2([[ERR:%.*]] : @owned $Error):
// CHECK: switch_enum %0 : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt: bb3, case #Optional.none!enumelt: bb4
// CHECK: bb3([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@guaranteed Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt, [[T1]] : $NSError
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$sSA7pointeexvs :
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
// CHECK: bb4:
// CHECK: destroy_value [[ERR]] : $Error
// CHECK: br bb5
// CHECK: bb5:
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, 0
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb6([[BOOL:%.*]] : $ObjCBool):
// CHECK: return [[BOOL]] : $ObjCBool
@objc func badDescription() throws -> String {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil hidden [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE14badDescriptionSSyKFTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> @autoreleased Optional<NSString> {
// CHECK: bb0([[UNOWNED_ARG0:%.*]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[UNOWNED_ARG1:%.*]] : @unowned $NSObject):
// CHECK: [[ARG1:%.*]] = copy_value [[UNOWNED_ARG1]]
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[T0:%.*]] = function_ref @$sSo8NSObjectC14foreign_errorsE14badDescriptionSSyKF : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error Error)
// CHECK: try_apply [[T0]]([[BORROWED_ARG1]]) : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error Error), normal [[NORMAL_BB:bb[0-9][0-9]*]], error [[ERROR_BB:bb[0-9][0-9]*]]
//
// CHECK: [[NORMAL_BB]]([[RESULT:%.*]] : @owned $String):
// CHECK: [[T0:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]]
// CHECK: [[T1:%.*]] = apply [[T0]]([[BORROWED_RESULT]])
// CHECK: end_borrow [[BORROWED_RESULT]]
// CHECK: [[T2:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[T1]] : $NSString
// CHECK: destroy_value [[RESULT]]
// CHECK: br bb6([[T2]] : $Optional<NSString>)
//
// CHECK: [[ERROR_BB]]([[ERR:%.*]] : @owned $Error):
// CHECK: switch_enum [[UNOWNED_ARG0]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9][0-9]*]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9][0-9]*]]
//
// CHECK: [[SOME_BB]]([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@guaranteed Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt, [[T1]] : $NSError
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$sSA7pointeexvs :
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
//
// CHECK: [[NONE_BB]]:
// CHECK: destroy_value [[ERR]] : $Error
// CHECK: br bb5
//
// CHECK: bb5:
// CHECK: [[T0:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt
// CHECK: br bb6([[T0]] : $Optional<NSString>)
//
// CHECK: bb6([[T0:%.*]] : @owned $Optional<NSString>):
// CHECK: end_borrow [[BORROWED_ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[T0]] : $Optional<NSString>
// CHECK-LABEL: sil hidden [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE7takeIntyySiKFTo : $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[SELF:%[0-9]+]] : @unowned $NSObject)
@objc func takeInt(_ i: Int) throws { }
// CHECK-LABEL: sil hidden [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE10takeDouble_3int7closureySd_S3iXEtKFTo : $@convention(objc_method) (Double, Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @convention(block) @noescape (Int) -> Int, NSObject) -> ObjCBool
// CHECK: bb0([[D:%[0-9]+]] : $Double, [[INT:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[CLOSURE:%[0-9]+]] : @unowned $@convention(block) @noescape (Int) -> Int, [[SELF:%[0-9]+]] : @unowned $NSObject):
@objc func takeDouble(_ d: Double, int: Int, closure: (Int) -> Int) throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
}
let fn = ErrorProne.fail
// CHECK-LABEL: sil private [ossa] @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_ : $@convention(thin) (@thick ErrorProne.Type) -> @owned @callee_guaranteed () -> @error Error {
// CHECK: [[T0:%.*]] = function_ref @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_yyKcfu0_ : $@convention(thin) (@thick ErrorProne.Type) -> @error Error
// CHECK-NEXT: [[T1:%.*]] = partial_apply [callee_guaranteed] [[T0]](%0)
// CHECK-NEXT: return [[T1]]
// CHECK-LABEL: sil private [ossa] @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_yyKcfu0_ : $@convention(thin) (@thick ErrorProne.Type) -> @error Error {
// CHECK: [[TEMP:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[SELF:%.*]] = thick_to_objc_metatype %0 : $@thick ErrorProne.Type to $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{%.*}}, [[SELF]])
// CHECK: cond_br
// CHECK: return
// CHECK: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK: [[T1:%.*]] = apply {{%.*}}([[T0]])
// CHECK: "willThrow"([[T1]] : $Error)
// CHECK: throw [[T1]]
func testArgs() throws {
try ErrorProne.consume(nil)
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors8testArgsyyKF : $@convention(thin) () -> @error Error
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: objc_method {{.*}} : $@objc_metatype ErrorProne.Type, #ErrorProne.consume!foreign : (ErrorProne.Type) -> (Any?) throws -> (), $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
func testBridgedResult() throws {
let array = try ErrorProne.collection(withCount: 0)
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors17testBridgedResultyyKF : $@convention(thin) () -> @error Error {
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: objc_method {{.*}} : $@objc_metatype ErrorProne.Type, #ErrorProne.collection!foreign : (ErrorProne.Type) -> (Int) throws -> [Any], $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> @autoreleased Optional<NSArray>
// CHECK: } // end sil function '$s14foreign_errors17testBridgedResultyyKF'
// rdar://20861374
// Clear out the self box before delegating.
class VeryErrorProne : ErrorProne {
init(withTwo two: AnyObject?) throws {
try super.init(one: two)
}
}
// SEMANTIC SIL TODO: _TFC14foreign_errors14VeryErrorPronec has a lot more going
// on than is being tested here, we should consider adding FileCheck tests for
// it.
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors14VeryErrorProneC7withTwoACyXlSg_tKcfc :
// CHECK: bb0([[ARG1:%.*]] : @owned $Optional<AnyObject>, [[ARG2:%.*]] : @owned $VeryErrorProne):
// CHECK: [[BOX:%.*]] = alloc_box ${ var VeryErrorProne }
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]]
// CHECK: [[LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_BOX]]
// CHECK: [[PB:%.*]] = project_box [[LIFETIME]]
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [lexical] [[ARG1]]
// CHECK: store [[ARG2]] to [init] [[PB]]
// CHECK: [[T0:%.*]] = load [take] [[PB]]
// CHECK-NEXT: [[T1:%.*]] = upcast [[T0]] : $VeryErrorProne to $ErrorProne
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK-NOT: [[BOX]]{{^[0-9]}}
// CHECK-NOT: [[PB]]{{^[0-9]}}
// CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]]
// CHECK-NEXT: [[DOWNCAST_BORROWED_T1:%.*]] = unchecked_ref_cast [[BORROWED_T1]] : $ErrorProne to $VeryErrorProne
// CHECK-NEXT: [[T2:%.*]] = objc_super_method [[DOWNCAST_BORROWED_T1]] : $VeryErrorProne, #ErrorProne.init!initializer.foreign : (ErrorProne.Type) -> (Any?) throws -> ErrorProne, $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @owned ErrorProne) -> @owned Optional<ErrorProne>
// CHECK: end_borrow [[BORROWED_T1]]
// CHECK: apply [[T2]]([[ARG1_COPY]], {{%.*}}, [[T1]])
// CHECK: } // end sil function '$s14foreign_errors14VeryErrorProneC7withTwoACyXlSg_tKcfc'
// rdar://21051021
// CHECK: sil hidden [ossa] @$s14foreign_errors12testProtocolyySo010ErrorProneD0_pKF : $@convention(thin) (@guaranteed ErrorProneProtocol) -> @error Error
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $ErrorProneProtocol):
func testProtocol(_ p: ErrorProneProtocol) throws {
// CHECK: [[T0:%.*]] = open_existential_ref [[ARG0]] : $ErrorProneProtocol to $[[OPENED:@opened(.*) ErrorProneProtocol]]
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $[[OPENED]], #ErrorProneProtocol.obliterate!foreign : {{.*}}
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, τ_0_0) -> ObjCBool
try p.obliterate()
// CHECK: [[T0:%.*]] = open_existential_ref [[ARG0]] : $ErrorProneProtocol to $[[OPENED:@opened(.*) ErrorProneProtocol]]
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $[[OPENED]], #ErrorProneProtocol.invigorate!foreign : {{.*}}
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, {{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, Optional<@convention(block) () -> ()>, τ_0_0) -> ObjCBool
try p.invigorate(callback: {})
}
// rdar://21144509 - Ensure that overrides of replace-with-() imports are possible.
class ExtremelyErrorProne : ErrorProne {
override func conflict3(_ obj: Any, error: ()) throws {}
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKF
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s14foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKFTo : $@convention(objc_method) (AnyObject, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, ExtremelyErrorProne) -> ObjCBool
// These conventions are usable because of swift_error. rdar://21715350
func testNonNilError() throws -> Float {
return try ErrorProne.bounce()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors15testNonNilErrorSfyKF :
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.bounce!foreign : (ErrorProne.Type) -> () throws -> Float, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Float
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: assign {{%.*}} to [[OPTERR]]
// CHECK: [[T0:%.*]] = load [take] [[OPTERR]]
// CHECK: switch_enum [[T0]] : $Optional<NSError>, case #Optional.some!enumelt: [[ERROR_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResult() throws -> CInt {
return try ErrorProne.ounce()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors19testPreservedResults5Int32VyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.ounce!foreign : (ErrorProne.Type) -> () throws -> Int32, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultBridged() throws -> Int {
return try ErrorProne.ounceWord()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors26testPreservedResultBridgedSiyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.ounceWord!foreign : (ErrorProne.Type) -> () throws -> Int, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int{{.*}}"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultInverted() throws {
try ErrorProne.once()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors27testPreservedResultInvertedyyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.once!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[ERROR_BB:bb[0-9]+]], [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return {{%.+}} : $()
// CHECK: [[ERROR_BB]]
// Make sure that we do not crash when emitting the error value here.
//
// TODO: Add some additional filecheck tests.
extension NSURL {
func resourceValue<T>(forKey key: String) -> T? {
var prop: AnyObject? = nil
_ = try? self.getResourceValue(&prop, forKey: key)
return prop as? T
}
}
|
apache-2.0
|
d3a4fcbb4159866cbd774c94a93abe48
| 60.832278 | 340 | 0.642766 | 3.432713 | false | true | false | false |
nifty-swift/Nifty
|
Sources/internal_helpers.swift
|
2
|
9264
|
/***************************************************************************************************
* _internal_helpers.swift
*
* This file provides miscellaneous helpers used internally by Nifty that aren't closely related to
* any other specific source file.
*
* Author: Phil Erickson
* Creation Date: 27 Dec 2016
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2016 Philip Erickson
**************************************************************************************************/
import Foundation
/// Enclose a given expression in parentheses if necessary.
///
/// If expression consists of a single literal then there is no need to enclose in parentheses,
/// since there would be no ambiguity when combined with another expression. If the expression
/// contains operators however, the expression may need parentheses to retain the same meaning when
/// combined with another expression.
///
/// For example, the expression exp="A" could be directly inserted into the expression "\(exp)^2"
/// withouth changing the meaning, yielding "A^2". However, exp="A+B" would need parentheses to
/// yield "(A+B)^2" otherwise the expression ("A+B^2") would not have the same meaning.
///
/// - Parameters:
/// - expression: expression to possibly parenthesize
/// - Returns: parenthesized expression, if needed
internal func _parenthesizeExpression(_ expression: String) -> String
{
// TODO: this can be fancier, perhaps use regular expressions when linux and mac converge
var expressionLiteralCharacters = CharacterSet.alphanumerics
expressionLiteralCharacters.insert("_")
// if expression is separated by whitespace, or contains any characters other than alphanumerics
// or the underscore, enclose in parentheses
if let _ = expression.rangeOfCharacter(from: expressionLiteralCharacters.inverted)
{
return "(\(expression))"
}
return expression
}
/// Create a new instance of a NumberFormatter, copying values from the given instance.
///
/// - Parameters:
/// - format: instance to copy
/// - Returns: new formatter instance
internal func _copyNumberFormatter(_ format: NumberFormatter) -> NumberFormatter
{
let fmt = NumberFormatter()
fmt.numberStyle = format.numberStyle
fmt.usesSignificantDigits = format.usesSignificantDigits
fmt.paddingCharacter = format.paddingCharacter
fmt.paddingPosition = format.paddingPosition
fmt.formatWidth = format.formatWidth
return fmt
}
/// Convert LAPACK pivot indices to permutation matrix.
///
/// From LAPACK description of ipiv: for 1 <= i <= min(M,N), row i of the matrix was interchanged
/// with row IPIV(i)/
///
/// For example: ipiv=[3,3,3]. This indicates that first row 1 of the matrix was changed with row 3,
/// then row 2 was changed with row 3, then row 3 was changed with row 3. These changes, when
/// applied to a 3x3 identity matrix, result in the permutation matrix P=[[0,0,1],[1,0,0],[0,1,0]].
///
/// - Parameters:
/// - ipiv: pivot indices; note LAPACK pivots are 1-indexed
/// - m: number of rows in matrix to permute
/// - n: number of columns in matrix to permute
/// - Returns: permutation matrix
internal func _ipiv2p(ipiv: [Int32], m: Int32, n: Int32) -> Matrix<Double>
{
// FIXME: revisit this for 1) correctness and 2) efficiency
// 1) currently just assuming the permutation matrix starts out as an mxn identity. Is that ok?
// 2) current impl is terribly inefficient, going through and performing each swap rather than
// resolving the final swaps and only doing those.
precondition(Int32(ipiv.count) == m, "Expected the number of pivot indices to match number of rows")
var P = eye(Int(m),Int(n))
for r in 0..<Int(m)
{
P = swap(rows: r, Int(ipiv[r])-1, in: P)
}
return P
}
/// Increment the first element of a given subscript, cascading carry values into the subsequent
/// element if possible.
///
/// Note: row-major order is assumed; last dimension increments quickest.
///
/// - Parameters:
/// - sub: subscript to increment
/// - min: min values for each element in list
/// - max: max values for each element in list
/// - Returns: incremented subscript or nil if list is already at max value
internal func _cascadeIncrementSubscript(_ sub: [Int], min: [Int], max: [Int]) -> [Int]?
{
let n = sub.count
precondition(min.count == n && max.count == n, "Subscript, min, and max must match in dimension")
var newSub = sub
newSub[n-1] += 1
for i in stride(from: n-1, through: 0, by: -1)
{
if newSub[i] > max[i]
{
if i == 0
{
return nil
}
newSub[i] = min[i]
newSub[i-1] = newSub[i-1] + 1
}
else
{
return newSub
}
}
return nil
}
/// Format a vector/matrix/tensor element according to the given formatter.
///
/// If there's an error in formatting, e.g. the element can't fit in the given space or number
/// formatting fails, a "#" is returned. Long non-numeric elements may be abbreviated by truncating
/// and adding "...".
///
/// - Parameters:
/// - element: element to format
/// - format: formatter to use; will not be modified by function
/// - Returns: formatted string representation; string will not be padded to a particular width, but
/// may include leading/trailing spaces to handle alignment (e.g. a leading space on positive
/// numbers to match the leading '-' on negatives)
internal func _formatElement<T>(_ element: T, _ format: NumberFormatter) -> String
{
// copy format since it's a reference type
let fmt = NumberFormatter()
fmt.numberStyle = format.numberStyle
fmt.usesSignificantDigits = format.usesSignificantDigits
fmt.paddingCharacter = format.paddingCharacter
fmt.paddingPosition = format.paddingPosition
fmt.formatWidth = format.formatWidth
// convert any numeric type to a double
let doubleValue: Double?
switch element
{
case is Double: doubleValue = (element as! Double)
case is Float: doubleValue = Double(element as! Float)
case is Float80: doubleValue = Double(element as! Float80)
case is Int: doubleValue = Double(element as! Int)
case is Int8: doubleValue = Double(element as! Int8)
case is Int16: doubleValue = Double(element as! Int16)
case is Int32: doubleValue = Double(element as! Int32)
case is Int64: doubleValue = Double(element as! Int64)
case is UInt: doubleValue = Double(element as! UInt)
case is UInt8: doubleValue = Double(element as! UInt8)
case is UInt16: doubleValue = Double(element as! UInt16)
case is UInt32: doubleValue = Double(element as! UInt32)
case is UInt64: doubleValue = Double(element as! UInt64)
default: doubleValue = nil
}
// format numbers and strings differently
if let el = doubleValue
{
var s = fmt.string(from: NSNumber(value: abs(el))) ?? "#"
// if element doesn't fit in desired width, format in minimal notation
if s.count > fmt.formatWidth
{
fmt.maximumSignificantDigits = fmt.formatWidth-4 // for 'E-99'
fmt.numberStyle = .scientific
s = fmt.string(from: NSNumber(value: abs(el))) ?? "#"
}
// TODO: come up with better way to handle padding...
// Rather than having all elements padded to a fixed width, the current approach is to strip
// all padding, then let the caller examine the collection of elements to be printed and
// determine the minimal padding necessary.
s = s.trimmingCharacters(in: .whitespacesAndNewlines)
let sign = el < 0 ? "-" : ""
s = sign + s
// TODO: NumberFormatter.Style.decimal shouldn't add commas according to current docs.
// But it does, so for now, strip commas. We should change this though to allow users to
// specify whether or not to use commas.
s = s.replacingOccurrences(of: ",", with: "")
return s
}
else
{
var s = "\(element)"
s = s.trimmingCharacters(in: .whitespacesAndNewlines)
// abbreviate or squash s if needed
if s.count > fmt.formatWidth
{
if fmt.formatWidth >= 4
{
let endIndex = s.index(s.startIndex, offsetBy: fmt.formatWidth-3)
s = s[s.startIndex..<endIndex] + "..."
}
else
{
s = "#"
}
}
return s
}
}
|
apache-2.0
|
8e8309f1f9f5174386fbf98e1732d340
| 35.329412 | 104 | 0.636658 | 4.351339 | false | false | false | false |
wangshengjia/LeeGo
|
Demo/LeeGo/MainViewController.swift
|
1
|
2278
|
//
// ViewController.swift
// PlaygroundProject
//
// Created by Victor WANG on 12/11/15.
// Copyright © 2015 Le Monde. All rights reserved.
//
import UIKit
import LeeGo
class MainViewController: UITableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
switch indexPath.row {
case 0:
cell.textLabel?.text = "Layout Samples"
case 1:
cell.textLabel?.text = "Le Monde"
case 2:
cell.textLabel?.text = "Twitter"
case 3:
cell.textLabel?.text = "Details Page"
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "SamplesViewController") as? SamplesViewController {
self.navigationController?.pushViewController(viewController, animated: true)
}
case 1:
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LeMondeNewsFeedViewController") as? LeMondeNewsFeedViewController {
self.navigationController?.pushViewController(viewController, animated: true)
}
case 2:
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "TwitterFeedViewController") as? TwitterFeedViewController {
self.navigationController?.pushViewController(viewController, animated: true)
}
case 3:
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "DetailsViewController") as? DetailsViewController {
self.navigationController?.pushViewController(viewController, animated: true)
}
default:
break
}
}
}
|
mit
|
948df196f0370f1ce7a356231cac41c7
| 33.5 | 163 | 0.654809 | 5.580882 | false | false | false | false |
hetefe/MyNews
|
MyNews/MyNews/Module/Search/SearchTableViewController.swift
|
1
|
3777
|
//
// SearchTableViewController.swift
// MyNews
//
// Created by 赫腾飞 on 15/12/23.
// Copyright © 2015年 hetefe. All rights reserved.
//
import UIKit
class SearchTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// tableView.backgroundColor = UIColor.darkGrayColor()
tableView.backgroundColor = UIColor(patternImage: UIImage(named: "lightWood")!)
setupUI()
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
private func setupUI(){
setNav()
}
private func setNav(){
title = "MyNews"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "left", style: .Plain, target: self, action: "presentLeftMenuViewController:")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "right", style: .Plain, target: self, action: "presentRightMenuViewController:")
}
@objc private func setSelf(){
print(__FUNCTION__)
}
@objc private func setting(){
print(__FUNCTION__)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
7fc02f78934cad7845ecc16cbb03deb5
| 30.932203 | 157 | 0.663217 | 5.437229 | false | false | false | false |
fengxinsen/ReadX
|
ReadX/BookRoomCell.swift
|
1
|
1590
|
//
// BookRoomCell.swift
// ReadMe
//
// Created by video on 2017/2/20.
// Copyright © 2017年 video. All rights reserved.
//
import Cocoa
import Kingfisher
class BookRoomCell: NSTableCellView {
@IBOutlet weak var mBookDelBtn: NSButtonCell!
@IBOutlet weak var mImageView: NSImageView!
@IBOutlet weak var mBookName: NSTextField!
@IBOutlet weak var mBookReadNew: NSTextField!
var mBook: Book! {
didSet {
mBookName.stringValue = mBook.bookName
let chapter = mBook.bookReadNew
mBookReadNew.stringValue = "最新:" + chapter
let url = URL.init(string: mBook.bookImage)
mImageView.kf.setImage(with: ImageResource.init(downloadURL: url!))
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
cellMenu()
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
@IBAction func bookDelAction(_ sender: NSButtonCell) {
deleteBook(book: mBook)
}
}
extension BookRoomCell {
func cellMenu() {
let menu = NSMenu.init()
menu.addItem(NSMenuItem.init(title: "打开", action: #selector(openAction(_:)), keyEquivalent: ""))
menu.addItem(NSMenuItem.init(title: "删除", action: #selector(delAction(_:)), keyEquivalent: ""))
self.menu = menu
}
func openAction(_ sender: NSMenuItem) {
openBook(book: mBook)
}
func delAction(_ sender: NSMenuItem) {
deleteBook(book: mBook)
}
}
|
mit
|
af5a3b27c617356e1cffb7f7faa77361
| 23.968254 | 104 | 0.607756 | 4.054124 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/Views/Cells/Auth/LoginServiceTableViewCell.swift
|
1
|
2757
|
//
// LoginServiceTableViewCell.swift
// Rocket.Chat
//
// Created by Filipe Alvarenga on 05/06/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
final class LoginServiceTableViewCell: UITableViewCell {
static let identifier = "LoginService"
static let rowHeight: CGFloat = 56.0
static let firstRowHeight: CGFloat = 82.0
static let lastRowHeight: CGFloat = 52.0
@IBOutlet weak var loginServiceButton: StyledButton!
@IBOutlet weak var loginServiceBottomConstraint: NSLayoutConstraint!
var defaultTextColor: UIColor!
var defaultBorderColor: UIColor!
var defaultButtonColor: UIColor!
var loginService: LoginService! {
didSet {
updateLoginService()
}
}
override func awakeFromNib() {
super.awakeFromNib()
defaultTextColor = loginServiceButton.textColor
defaultBorderColor = loginServiceButton.borderColor
defaultButtonColor = loginServiceButton.buttonColor
}
func updateLoginService() {
if let icon = loginService.type.icon {
loginServiceButton.style = .outline
loginServiceButton.textColor = defaultTextColor
loginServiceButton.borderColor = defaultBorderColor
loginServiceButton.buttonColor = defaultButtonColor
loginServiceButton.applyStyle()
let font = UIFont.preferredFont(forTextStyle: .body)
let prefix = NSAttributedString(
string: localized("auth.login_service_prefix"),
attributes: [
NSAttributedString.Key.font: font
]
)
let service = NSAttributedString(
string: loginService.service?.capitalized ?? "",
attributes: [
NSAttributedString.Key.font: font.bold() ?? font
]
)
let combinedString = NSMutableAttributedString(attributedString: prefix)
combinedString.append(service)
loginServiceButton.setAttributedTitle(combinedString, for: .normal)
loginServiceButton.setImage(icon, for: .normal)
} else {
loginServiceButton.style = .solid
loginServiceButton.textColor = UIColor(hex: loginService.buttonLabelColor)
loginServiceButton.borderColor = .clear
loginServiceButton.buttonColor = UIColor(hex: loginService.buttonColor)
loginServiceButton.fontTraits = .traitBold
loginServiceButton.applyStyle()
loginServiceButton.setTitle(loginService.buttonLabelText, for: .normal)
}
}
}
// MARK: Disable Theming
extension LoginServiceTableViewCell {
override func applyTheme() { }
}
|
mit
|
7613e56a5ba0f07aa747885082907834
| 32.204819 | 86 | 0.652758 | 5.310212 | false | false | false | false |
rtsbtx/EasyIOS-Swift
|
Pod/Classes/Easy/Lib/EZPrintln.swift
|
4
|
1293
|
//
// EZPrintln.swift
// medical
//
// Created by zhuchao on 15/4/28.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import Foundation
var EZ_DEBUG_MODE = true
/**
Writes the textual representation of `object` and a newline character into the standard output.
The textual representation is obtained from the `object` using its protocol conformances,
in the following order of preference: `Streamable`, `Printable`, `DebugPrintable`.
This functional also augments the original function with the filename, function name, and line number of the object that is being logged.
:param: object A textual representation of the object.
:param: file Defaults to the name of the file that called magic(). Do not override this default.
:param: function Defaults to the name of the function within the file in which magic() was called. Do not override this default.
:param: line Defaults to the line number within the file in which magic() was called. Do not override this default.
*/
public func EZPrintln<T>(object: T, _ file: String = __FILE__, _ function: String = __FUNCTION__, _ line: Int = __LINE__)
{
if EZ_DEBUG_MODE {
let filename = file.lastPathComponent.stringByDeletingPathExtension
print("\(filename).\(function)[\(line)]: \(object)\n")
}
}
|
mit
|
ce8f4c01f018ab28541639c35295f956
| 43.517241 | 137 | 0.725794 | 4.191558 | false | false | false | false |
ApacheExpress/ApacheExpress3
|
Sources/ApacheExpress3/ApacheReloadMiddleware.swift
|
1
|
1956
|
//
// ApacheReloadMiddleware.swift
// ApacheExpress3
//
// Created by Helge Hess on 09/05/17.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
/**
* A simple middleware which simply sends the `SIGHUP` signal to the Apache
* master process.
* This tells Apache to perform a graceful restart. That is the configuration
* and modules are reloaded, but the child processes are allowed to finish up
* the connections they are currently processing.
*
* By default this middleware is restricted to the `development` environment
* for hopefully obvious reasons :->
*
* Note: This does NOT work for an Apache instance run from within Xcode.
* This is because our Xcode configs start Apache in debug mode (`-X`),
* which means it doesn't fork.
*
* IMPORTANT: Be careful w/ using that extension. It is best to turn in off
* completely in deployments.
*/
public func apacheReload(enabledIn: [ String ] = [ "development" ])
-> Middleware
{
return { req, res, _ in
guard let env = req.app?.settings.env, enabledIn.contains(env) else {
// TBD: well, how do I just cancel this specific route and bubble up? We
// could throw a specific error? (Route.Skip?)
console.warn("attempt to access apache-reload in disabled env:",
req.app?.settings.env, req)
return try res.sendStatus(404) // FIXME
}
guard !process.isRunningInXCode else {
res.statusCode = 403
return try res.json([
"error": 403,
"message": "Cannot reload Apache when it is running in Xcode!"
])
}
let pid = getpid()
let ppid = getppid()
console.log("\(pid): sending SIGHUP to parent process \(ppid) ...")
kill(ppid, SIGHUP)
console.log("done.")
return try res.json([
"processID": pid,
"parentProcessID": ppid
])
}
}
#if os(Linux)
import Glibc
#else
import Darwin
#endif
|
apache-2.0
|
175aa7123c35359b725bf76a9076cf4f
| 29.076923 | 78 | 0.642455 | 3.949495 | false | false | false | false |
davidiola/BitExplorer
|
registerViewController.swift
|
1
|
5628
|
//
// registerViewController.swift
// BitExplorer
//
// Created by David Iola on 2/25/17.
// Copyright © 2017 David Iola. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class registerViewController: UIViewController {
@IBOutlet weak var iconFirst: UILabel!
@IBOutlet weak var iconLast: UILabel!
@IBOutlet weak var iconEmail: UILabel!
@IBOutlet weak var iconPass: UILabel!
@IBOutlet weak var iconConfirm: UILabel!
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var confirmField: UITextField!
var ref: FIRDatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(registerViewController.dismissKeyboard)))
iconFirst.font = UIFont.fontAwesome(ofSize: 20)
iconFirst.text = String.fontAwesomeIcon(name: .user)
iconLast.font = UIFont.fontAwesome(ofSize: 20)
iconLast.text = String.fontAwesomeIcon(name: .user)
iconEmail.font = UIFont.fontAwesome(ofSize: 18)
iconEmail.text = String.fontAwesomeIcon(name: .envelope)
iconPass.font = UIFont.fontAwesome(ofSize: 20)
iconPass.text = String.fontAwesomeIcon(name: .unlockAlt)
iconConfirm.font = UIFont.fontAwesome(ofSize: 20)
iconConfirm.text = String.fontAwesomeIcon(name: .key)
ref = FIRDatabase.database().reference()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil);
}
func dismissKeyboard() {
firstName.resignFirstResponder()
lastName.resignFirstResponder()
emailField.resignFirstResponder()
passwordField.resignFirstResponder()
confirmField.resignFirstResponder()
}
@IBAction func submitTapped(_ sender: Any) {
let firstname = firstName.text;
let lastname = lastName.text;
let email = emailField.text;
let password = passwordField.text;
let confirm = confirmField.text;
if ( (firstname!.isEmpty || lastname!.isEmpty || email!.isEmpty || password!.isEmpty || confirm!.isEmpty)) {
//display alert message
displayMyAlertMessage("All fields are required");
return;
}
if (password != confirm) {
//Display alert message
displayMyAlertMessage("Passwords do not match");
return;
}
// store on Firebase
FIRAuth.auth()?.createUser(withEmail: email!, password: password!) { (user, error) in
if error == nil {
let userUID = FIRAuth.auth()?.currentUser?.uid
self.ref.child("users").child(userUID!).setValue(["First" : firstname, "Last" : lastname])
let myAlert = UIAlertController(title: "Alert", message: "Registration is Successful", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) {
action in
self.performSegue(withIdentifier: "loginSegue", sender: self);
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil);
}
else {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
func displayMyAlertMessage(_ userMessage:String) {
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil);
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil);
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
6d9a2906d594c91056c2f325aeff4eef
| 28.307292 | 149 | 0.564066 | 5.795057 | false | false | false | false |
ColinConduff/BlocFit
|
BlocFit/Auxiliary Components/Run History/Run History Cell/RunHistoryTableViewCell.swift
|
1
|
1082
|
//
// RunHistoryTableViewCell.swift
// BlocFit
//
// Created by Colin Conduff on 11/13/16.
// Copyright © 2016 Colin Conduff. All rights reserved.
//
import UIKit
class RunHistoryTableViewCell: UITableViewCell {
@IBOutlet weak var timeIntervalLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var numRunnersLabel: UILabel!
@IBOutlet weak var paceLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
var controller: RunHistoryCellController? {
didSet {
guard let controller = controller else { return }
timeIntervalLabel?.text = controller.time
scoreLabel?.text = controller.score
numRunnersLabel?.text = controller.numRunners
paceLabel?.text = controller.pace
distanceLabel?.text = controller.distance
}
}
}
|
mit
|
38d7349e568bdb4250f1a0ccd9a8abf1
| 26.717949 | 65 | 0.654949 | 4.762115 | false | false | false | false |
raman049/Vogel_swift
|
GameScene.swift
|
1
|
52405
|
//
// GameScene.swift
// Vogel
//
// Created by raman maharjan on 12/28/16.
// Copyright © 2016 raman maharjan. All rights reserved.
//
import SpriteKit
import GameplayKit
import GameKit
import Darwin
import AVFoundation
import Social
import Firebase;
import GoogleMobileAds
import UIKit
struct PhysicsCategory {
static let bird : UInt32 = 0x1 << 1
static let plane : UInt32 = 0x1 << 2
static let fly : UInt32 = 0x1 << 3
static let ship : UInt32 = 0x1 << 4
static let cloud : UInt32 = 0x1 << 5
static let shark : UInt32 = 0x1 << 6
static let lightning : UInt32 = 0x1 << 7
static let tree : UInt32 = 0x1 << 8
static let pineappletree : UInt32 = 0x1 << 9
}
class GameScene: SKScene, SKPhysicsContactDelegate, GKGameCenterControllerDelegate,GADBannerViewDelegate {
var interstitial: GADInterstitial!
var bird2 = SKSpriteNode()
var bird1 = SKSpriteNode()
var bird = SKSpriteNode()
var lightning = SKSpriteNode()
var fruit = SKSpriteNode()
var boom = SKSpriteNode()
var shark = SKSpriteNode()
var fly = SKSpriteNode()
var wavea = SKSpriteNode()
var jetpair = SKNode()
var jetpair2 = SKNode()
var cloudNode = SKNode()
var cloudNode2 = SKNode()
var cloudNode3 = SKNode()
var shipNode = SKNode()
var sharkNode = SKNode()
var flyNode = SKNode()
var treeNode = SKNode()
var treeNodePineapple = SKNode()
var waveNode = SKNode()
var started = Bool()
var gameOver = Bool()
var birdHitCloud = Bool()
var birdHitWave = Bool()
var birdHitJet = Bool()
var birdHitFly = Bool()
var birdHitTree = Bool()
var addTreeFruit = Bool()
var birdHitPineappleTree = Bool()
var fruitBonus = Bool()
var fruitBonusPineapple = Bool()
var moveAndRemove = SKAction()
var moveAndRemove2 = SKAction()
var moveAndRemoveCloud = SKAction()
var moveAndRemoveShip = SKAction()
var moveAndRemoveShark = SKAction()
var moveAndRemoveFly = SKAction()
var moveAndRemoveTree = SKAction()
var moveAndRemoveWave = SKAction()
var labelHiScore = UILabel()
var labelHiScoreInt = UILabel()
var scoreLabel = UILabel()
var labelScoreInt = UILabel()
var taptoStart = UILabel()
var bonus = UILabel()
var finalScoreInt = Int()
var count = Int()
var scoreInt = 0
var replay = UIButton()
var gameOverText = UILabel()
var gcButton = UIButton()
var fbButton = UIButton()
var instructionQueBut = UIButton()
var player: AVAudioPlayer?
var audioPlayer: AVAudioPlayer?
var playerLight: AVAudioPlayer?
var playerBubble: AVAudioPlayer?
var highScore = Int()
var soundIsland: AVAudioPlayer?
var latinhorn: AVAudioPlayer?
var count1: CGFloat = CGFloat(0)
var adBannerView = GADBannerView()
var screenShot = UIImage()
var InjuredBirdimage = SKSpriteNode()
var InjuredBird = UIImageView()
var image0 = UIGraphicsGetImageFromCurrentImageContext()
override func didMove(to view: SKView) {
getItTogether()
}
func getItTogether(){
authPlayer()
startNewGame()
// setup physics
self.physicsWorld.gravity = CGVector( dx: 0.0, dy: -2 )
self.physicsWorld.contactDelegate = self
backgroundColor = UIColor.init(red: 153/255, green: 204/255, blue: 1, alpha: 1.0)
//play island sound
soundIsland = playIsland()
soundIsland?.numberOfLoops = -1
soundIsland?.play()
//add waves
wavea = SKSpriteNode(imageNamed: "wave2")
let waveb = SKSpriteNode(imageNamed: "wave2")
let wavec = SKSpriteNode(imageNamed: "wave2")
let waved = SKSpriteNode(imageNamed: "wave2")
let wavee = SKSpriteNode(imageNamed: "wave2")
let wavef = SKSpriteNode(imageNamed: "wave2")
let waveg = SKSpriteNode(imageNamed: "wave2")
let waveSz = CGSize(width: wavea.size.width, height: wavea.size.height)
wavea.size = waveSz
// wavea.scale(to: waveSz)
wavea.position = CGPoint(x: (Int) (wavea.size.width/2) , y: (Int)(wavea.size.height/3))
addChild(wavea)
// waveb.scale(to: waveSz)
waveb.size = waveSz
wavec.size = waveSz
waved.size = waveSz
wavee.size = waveSz
wavef.size = waveSz
waveg.size = waveSz
waveb.position = CGPoint(x: (Int) (wavea.size.width/2) * 3 - 5 , y: (Int) (wavea.size.height/3))
addChild(waveb)
// wavec.scale(to: waveSz)
wavec.position = CGPoint(x: (Int) (wavea.size.width/2) * 5 - 10 , y: (Int) (wavea.size.height/3))
addChild(wavec)
// waved.scale(to: waveSz)
waved.position = CGPoint(x: (Int) (wavea.size.width/2) * 7 - 20 , y: (Int) (wavea.size.height/3))
addChild(waved)
// wavee.scale(to: waveSz)
wavee.position = CGPoint(x: (Int) (wavea.size.width/2) * 9 - 30 , y: (Int) (wavea.size.height/3))
addChild(wavee)
// wavef.scale(to: waveSz)
wavef.position = CGPoint(x: (Int) (wavea.size.width/2) * 11 - 40 , y: (Int) (wavea.size.height/3))
addChild(wavef)
// waveg.scale(to: waveSz)
waveg.position = CGPoint(x: (Int) (wavea.size.width/2) * 13 - 40 , y: (Int) (wavea.size.height/3))
addChild(waveg)
//add SUn
let sun = SKSpriteNode(imageNamed: "sun")
let sunSz = CGSize(width: sun.size.width/2 , height: sun.size.height/2)
// sun.scale(to: sunSz)
sun.size = sunSz
sun.zRotation = CGFloat(.pi/2.0)
sun.anchorPoint = CGPoint(x:CGFloat(0.5),y:CGFloat(0.5))
sun.position = CGPoint(x: size.width - sun.size.width - 5, y: size.height - sun.size.height)
let spin = SKAction.rotate(byAngle: CGFloat.pi, duration: 10)
let spinForever = SKAction.repeatForever(spin)
sun.run(spinForever)
addChild(sun)
//add HighScore
labelHiScore = UILabel(frame: CGRect(x: self.size.width/2 - 100, y: self.size.height/5 - 10, width: 200, height: 30))
labelHiScore.textAlignment = .center
labelHiScore.textColor = UIColor.red
labelHiScore.font = UIFont.init(name: "MarkerFelt-Thin", size: 20)
let userDefaults = UserDefaults.standard
let highscore3 = userDefaults.value(forKey: "highscore")
labelHiScore.text = "Hi Score: \(highscore3!)"
self.view?.addSubview(labelHiScore)
//tap to start
taptoStart = UILabel(frame: CGRect(x: self.size.width/2 - 250, y: self.size.height/2 - 50, width: 500, height: 100))
// taptoStart.center = CGPoint(x: self.size.width/2, y: self.size.height/5)
taptoStart.textAlignment = .center
taptoStart.textColor = UIColor.yellow
taptoStart.font = UIFont.init(name: "MarkerFelt-Thin", size: 75)
taptoStart.text = "Tap To Start"
self.view?.addSubview(taptoStart)
//add Birdx
bird = SKSpriteNode(imageNamed: "bird1")
let birdSz = CGSize(width: (bird.size.width/3) * 2, height: (bird.size.height/3) * 2)
let birdPhysicsSz = CGSize(width: bird.size.width/3, height: bird.size.height/3)
//bird.scale(to: birdSz)
bird.size = birdSz
bird.position = CGPoint(x: self.size.width/3, y: self.size.height/2 - 10 )
bird.physicsBody = SKPhysicsBody(rectangleOf: birdPhysicsSz)
bird.physicsBody?.isDynamic = true
bird.zPosition = 2
bird.physicsBody?.allowsRotation = false
bird.physicsBody?.affectedByGravity = false
bird.physicsBody?.categoryBitMask = PhysicsCategory.bird
bird.physicsBody?.collisionBitMask = PhysicsCategory.plane | PhysicsCategory.cloud | PhysicsCategory.ship
bird.physicsBody?.contactTestBitMask = PhysicsCategory.plane | PhysicsCategory.cloud | PhysicsCategory.ship
self.addChild(bird)
}
override func update(_ currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if started == true && gameOver == false {
if bird.position.y < wavea.size.height { //bird hit water
birdHitWave = true
}
if bird.position.y > self.size.height{ // bird touches sky
// birdHitCloud = true
bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: -2))
}
}
if (birdHitCloud){
addLightning()
soundIsland?.stop()
let s3: AVAudioPlayer = playElectric()
s3.play()
Timer.scheduledTimer(timeInterval: TimeInterval(0.7), target: self, selector: #selector(GameScene.gameOverMethod), userInfo: nil, repeats: false)
}
if (birdHitWave){
addShark()
soundIsland?.stop()
let s5: AVAudioPlayer = playBubble()
s5.play()
Timer.scheduledTimer(timeInterval: TimeInterval(0.7), target: self, selector: #selector(GameScene.gameOverMethod), userInfo: nil, repeats: false)
}
if (birdHitJet){
addBoom()
soundIsland?.stop()
let soudHitJet: AVAudioPlayer = playBoom()
soudHitJet.play()
Timer.scheduledTimer(timeInterval: TimeInterval(0.7), target: self, selector: #selector(GameScene.gameOverMethod), userInfo: nil, repeats: false)
}
if birdHitTree == true {
addTreeFruit = true
addFruit()
scoreInt = scoreInt + 500
fruitBonus = true
addBonus()
let coconutSound: AVAudioPlayer = playTree()
coconutSound.volume = 0.9
coconutSound.play()
birdHitTree = false
}
if birdHitPineappleTree == true {
scoreInt = scoreInt + 1000
addFruit()
fruitBonusPineapple = true
addBonus()
let coconutSound: AVAudioPlayer = playTree()
coconutSound.volume = 0.9
coconutSound.play()
birdHitPineappleTree = false
}
if birdHitFly == true{
scoreInt = scoreInt + 50
addBonus()
let flySound: AVAudioPlayer = playFly()
flySound.volume = 0.9
flySound.play()
birdHitFly = false
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
bird.texture = SKTexture(imageNamed:"bird2")
// add highscore
if gameOver == false {
labelHiScore.removeFromSuperview()
labelHiScore = UILabel(frame: CGRect(x: self.size.width/80 , y: 10, width: 300, height: 20))
labelHiScore.font = UIFont.init(name: "Georgia-Italic", size: 10)
labelHiScore.textColor = UIColor.blue
// labelHiScore.textAlignment = .right
let userDefaults = UserDefaults.standard
let highscore4 = userDefaults.value(forKey: "highscore")
let hs = highscore4 as! NSNumber
labelHiScoreInt.removeFromSuperview()
labelHiScoreInt = UILabel(frame: CGRect(x: self.size.width/80 , y: 10 + 8, width: 300, height: 20))
labelHiScoreInt.font = UIFont.init(name: "Georgia-Italic", size: 10)
labelHiScoreInt.textColor = UIColor.blue
// labelHiScoreInt.textAlignment = .right
labelHiScore.text = "High Score:"
labelHiScoreInt.text = "\(hs)"
self.view?.addSubview(labelHiScore)
self.view?.addSubview(labelHiScoreInt)
//add score
scoreLabel.removeFromSuperview()
scoreLabel = UILabel(frame: CGRect(x: self.size.width/80 , y: 20 + 10 , width: 150, height: 20))
//scoreLabel.textAlignment = .center
scoreLabel.textColor = UIColor.blue
scoreLabel.font = UIFont.init(name:"Georgia-Italic", size: 10)
labelScoreInt.removeFromSuperview()
labelScoreInt = UILabel(frame: CGRect(x: self.size.width/80 , y: 26 + 15, width: 150, height: 20))
// labelScoreInt.textAlignment = .center
labelScoreInt.textColor = UIColor.blue
labelScoreInt.font = UIFont.init(name:"Georgia-Italic", size: 15)
scoreLabel.text = "Your Score:"
labelScoreInt.text = "\(scoreInt)"
self.view?.addSubview(scoreLabel)
self.view?.addSubview(labelScoreInt)
}
if started == false {
started = true
taptoStart.isHidden = true
bird.physicsBody?.affectedByGravity = true
//creates a block
//move and remove jet
let removeFromParent = SKAction.removeFromParent()
let distance = CGFloat(self.frame.width + jetpair.frame.width + 275 )
let distanceCloud = CGFloat(self.frame.width * 3 + 275 )
let movingJet = SKAction.run({
() in
self.addjets()
})
let delay = SKAction.wait(forDuration: 2) //interval between jets
let addJetDelay = SKAction.sequence ([movingJet, delay])
let addJetForever = SKAction.repeatForever(addJetDelay)
self.run(addJetForever)
let movePlane = SKAction.moveBy(x: -distance , y:0, duration: TimeInterval(5))
moveAndRemove = SKAction.sequence([movePlane, removeFromParent])
//move and remove jet2
let movingJet2 = SKAction.run({
() in
self.addjets2()
})
let delayJet2 = SKAction.wait(forDuration: 4) //interval between jets
let addJet2Delay = SKAction.sequence ([movingJet2, delayJet2])
let addJet2Forever = SKAction.repeatForever(addJet2Delay)
self.run(addJet2Forever)
let movePlane2 = SKAction.moveBy(x: -distance , y:0, duration: TimeInterval(3))
moveAndRemove2 = SKAction.sequence([movePlane2, removeFromParent])
//move and remove fly
let movingFly = SKAction.run({
() in
self.addFly()
})
let delayFly = SKAction.wait(forDuration: 8) //interval between jets
let addFlyDelay = SKAction.sequence ([movingFly, delayFly])
let addFlyForever = SKAction.repeatForever(addFlyDelay)
self.run(addFlyForever)
let moveFly = SKAction.moveBy(x: -distance , y:0, duration: TimeInterval(12))
moveAndRemoveFly = SKAction.sequence([moveFly, removeFromParent])
//move and remove tree
let movingTree = SKAction.run({
() in
self.addTree()
self.addTreePineapple()
})
let delayTree = SKAction.wait(forDuration: 33) //interval between jets
let addTreeDelay = SKAction.sequence ([movingTree, delayTree])
let addTreeForever = SKAction.repeatForever(addTreeDelay)
self.run(addTreeForever)
let moveTree = SKAction.moveBy(x: -distance , y:0, duration: TimeInterval(33))
moveAndRemoveTree = SKAction.sequence([moveTree, removeFromParent])
//move and remove cloud
let movingCloud = SKAction.run({
() in
self.addCloud()
self.addCloud2()
self.addCloud3()
})
let delayCloud = SKAction.wait(forDuration: 4) //interval between jets
let addCloudDelay = SKAction.sequence ([movingCloud, delayCloud])
let addCloudForever = SKAction.repeatForever(addCloudDelay)
self.run(addCloudForever)
let moveCloud = SKAction.moveBy(x: -distanceCloud , y:0, duration: TimeInterval(15))
moveAndRemoveCloud = SKAction.sequence([moveCloud, removeFromParent])
//move and remove ship
let movingShip = SKAction.run({
() in
self.addShip()
})
let delay2 = SKAction.wait(forDuration: 50) //interval between jets
let addShipDelay = SKAction.sequence ([movingShip, delay2])
let addShipForever = SKAction.repeatForever(addShipDelay)
self.run(addShipForever)
let moveShip = SKAction.moveBy(x: distance , y:0, duration: TimeInterval(50))
moveAndRemoveShip = SKAction.sequence([moveShip, removeFromParent])
//move and remove Wave
let movingwave = SKAction.run({
() in
self.addWavea()
self.addWaveb()
self.addWavec()
self.addWaved()
self.addWavee()
self.addWavef()
})
let delayWave = SKAction.wait(forDuration: 0.3)
let addWaveDelay = SKAction.sequence ([movingwave, delayWave])
let addWaveForever = SKAction.repeatForever(addWaveDelay)
self.run(addWaveForever)
let moveWave = SKAction.moveBy(x: 200 , y: 0, duration: TimeInterval(1))
moveAndRemoveWave = SKAction.sequence([moveWave, removeFromParent])
bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 3))
}else{
bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 3))
}
if started == true && gameOver == false {
scoreInt += 1
let userDefaults = UserDefaults.standard
let highScoreValue = userDefaults.value(forKey: "highscore")
let hsv: Int? = highScoreValue as! Int?
if hsv! < scoreInt {
highScore = scoreInt
userDefaults.setValue(highScore, forKey: "highscore")
saveHS(number: highScoreValue as! Int)
userDefaults.synchronize()
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if started == true && gameOver == false {
bird.texture = SKTexture(imageNamed:"bird1")
let s1: AVAudioPlayer = playBird()
s1.numberOfLoops = 1
s1.play()
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
}
func gameOverMethod() {
gameOver = true
soundIsland?.stop()
addads1I()
self.removeAllChildren()
self.removeAllActions()
replay.isHidden = true
banner()
//play spanish horn music
latinhorn = playlatinHorn()
latinhorn?.numberOfLoops = -1
latinhorn?.play()
backgroundColor = UIColor.init(red: 0, green: 0, blue: 200/255, alpha: 255/255)
labelHiScore.removeFromSuperview()
labelHiScore = UILabel(frame: CGRect(x: self.size.width/3 - 150, y: self.size.height/10 , width: 300, height: 30))
labelHiScore.textAlignment = .center
labelHiScore.font = UIFont.init(name: "Georgia-Italic", size: 25)
labelHiScore.textColor = UIColor.init(red: 1, green: 1, blue: 0, alpha: 255/255)
let userDefaults = UserDefaults.standard
let highscore5 = userDefaults.value(forKey: "highscore")
labelHiScoreInt.removeFromSuperview()
labelHiScoreInt = UILabel(frame: CGRect(x: self.size.width/3 - 150, y: self.size.height/10 + 25 , width: 300, height: 40))
labelHiScoreInt.textAlignment = .center
labelHiScoreInt.font = UIFont.init(name: "Georgia-Italic", size: 40)
labelHiScoreInt.textColor = UIColor.init(red: 1, green: 1, blue: 0, alpha: 255/255)
labelHiScore.text = "High Score:"
labelHiScoreInt.text = "\(highscore5!)"
self.view?.addSubview(labelHiScore)
self.view?.addSubview(labelHiScoreInt)
scoreLabel.removeFromSuperview()
scoreLabel = UILabel(frame: CGRect(x: self.size.width - self.size.width/3 - 150, y: self.size.height/10 , width: 300, height: 30))
scoreLabel.textAlignment = .center
scoreLabel.textColor = UIColor.init(red: 1, green: 1, blue: 0, alpha: 255/255)
scoreLabel.font = UIFont.init(name: "Georgia-Italic", size: 25)
scoreLabel.text = "Your Score:"
self.view?.addSubview(scoreLabel)
labelScoreInt.removeFromSuperview()
labelScoreInt = UILabel(frame: CGRect(x: self.size.width - self.size.width/3 - 150, y: self.size.height/10 + 25, width: 300, height: 40))
labelScoreInt.textAlignment = .center
labelScoreInt.textColor = UIColor.init(red: 1, green: 1, blue: 0, alpha: 255/255)
labelScoreInt.font = UIFont.init(name: "Georgia-Italic", size: 40)
labelScoreInt.text = "\(scoreInt)"
self.view?.addSubview(labelScoreInt)
InjuredBird.removeFromSuperview()
InjuredBirdimage.removeFromParent()
InjuredBirdimage = SKSpriteNode(imageNamed: "InjuredBird")
InjuredBird = UIImageView(frame:CGRect(x:self.size.width/2 - (InjuredBirdimage.size.width * 3)/2, y: self.size.height/3, width: InjuredBirdimage.size.width * 3, height: InjuredBirdimage.size.height * 3))
InjuredBird.image = UIImage(named: "InjuredBird")!
self.view?.addSubview(InjuredBird)
//add Replay button
let replayImage = UIImage(named: "replay") as UIImage?
replay = UIButton(type: UIButtonType.custom) as UIButton
replay.frame = CGRect(x: self.size.width - 20 - (replayImage?.size.width)!/3 , y: self.size.height - 10 - (replayImage?.size.height)!/3, width: (replayImage?.size.width)!/3, height: (replayImage?.size.height)!/3)
replay.setImage(replayImage, for: .normal)
replay.addTarget(self, action: #selector(GameScene.restartMethod), for: .touchUpInside)
self.view?.addSubview(replay)
// add instruction
let instructionQueImg = UIImage(named: "instructionQue") as UIImage?
instructionQueBut.removeFromSuperview()
instructionQueBut = UIButton(type: UIButtonType.custom) as UIButton
instructionQueBut.frame = CGRect(x: 10, y: self.size.height - 10 - (instructionQueImg?.size.height)!/3, width: (instructionQueImg?.size.width)!/3, height: (instructionQueImg?.size.height)!/3)
instructionQueBut.setImage(instructionQueImg, for: .normal)
instructionQueBut.addTarget(self, action: #selector(GameScene.popUp), for: .touchUpInside)
self.view?.addSubview(instructionQueBut)
//add gc
let gcButtonImage = UIImage(named: "scoreboard") as UIImage?
gcButton.removeFromSuperview()
gcButton = UIButton(type: UIButtonType.custom) as UIButton
gcButton.frame = CGRect(x: 20 + (gcButtonImage?.size.width)!/3 , y: self.size.height - 10 - (gcButtonImage?.size.height)!/3, width: (gcButtonImage?.size.width)!/3, height: (gcButtonImage?.size.height)!/3)
gcButton.setImage(gcButtonImage, for: .normal)
gcButton.addTarget(self, action: #selector(GameScene.showGC), for: .touchUpInside)
self.view?.addSubview(gcButton)
//add fb
let fbButtonImage = UIImage(named: "fblogo") as UIImage?
fbButton.removeFromSuperview()
fbButton = UIButton(type: UIButtonType.custom) as UIButton
fbButton.frame = CGRect(x: 10 , y: self.size.height - 20 - ((fbButtonImage?.size.height)!/3)*2, width: (fbButtonImage?.size.width)!/3, height: (fbButtonImage?.size.height)!/3)
fbButton.setImage(fbButtonImage, for: .normal)
fbButton.addTarget(self, action: #selector(GameScene.showFacebook), for: .touchUpInside)
self.view?.addSubview(fbButton)
}
var customView = UIView()
var backButton = UIButton()
var instruction = UIImageView()
var scoreboard = UIImageView()
func popUp()
{
//add custom uiview for popup
replay.isEnabled = false
customView.removeFromSuperview()
customView = UIView(frame: CGRect(x: 50, y: 50, width: self.size.width - 100 , height: self.size.height - 100))
customView.backgroundColor = UIColor.init(red: 196/255, green: 113/255, blue: 245/255, alpha: 255/255)
//add image in uiview
instruction.removeFromSuperview()
instruction = UIImageView(frame:CGRect(x: 50, y: 50, width: self.size.width - 100 , height: self.size.height - 100))
instruction.image = UIImage(named: "instruction2")!
self.view?.addSubview(customView)
self.view?.addSubview(instruction)
// add back button
let backButtonImg = UIImage(named: "close") as UIImage?
backButton.removeFromSuperview()
backButton = UIButton(type: UIButtonType.custom) as UIButton
backButton.frame = CGRect(x: 10, y: 10, width: (backButtonImg?.size.width)!/3, height: (backButtonImg?.size.height)!/3)
backButton.setImage(backButtonImg, for: .normal)
backButton.removeFromSuperview()
backButton.addTarget(self, action: #selector(GameScene.closeView), for: .touchUpInside)
self.view?.addSubview(backButton)
}
func closeView(sender:UIButton)
{
replay.isEnabled = true
customView.removeFromSuperview()
backButton.removeFromSuperview()
instruction.removeFromSuperview()
}
func restartMethod(){
latinhorn?.stop()
taptoStart.isHidden = true
self.removeAllChildren()
self.removeAllActions()
self.removeFromParent()
gcButton.isEnabled = true
InjuredBird.removeFromSuperview()
adBannerView.removeFromSuperview()
gcButton.removeFromSuperview()
fbButton.removeFromSuperview()
instructionQueBut.removeFromSuperview()
gameOverText.isEnabled = false
gameOverText.removeFromSuperview()
scoreLabel.removeFromSuperview()
replay.removeFromSuperview()
labelHiScore.removeFromSuperview()
labelScoreInt.removeFromSuperview()
labelHiScoreInt.removeFromSuperview()
gameOver = false
started = false
scoreInt = 0
getItTogether()
}
func addjets(){
jetpair = SKNode()
let plane = SKSpriteNode(imageNamed: "plane1")
let heighta = self.size.height - wavea.size.height * 2
let randomPosition2 = CGFloat(arc4random_uniform(UInt32(heighta)))
let planeSz = CGSize(width: plane.size.width * 6/5 , height: plane.size.height * 6/5 )
let planePhysicsSz = CGSize(width: plane.size.width/2 , height: plane.size.height/4)
// plane.scale(to: planeSz)
plane.size = planeSz
plane.position = CGPoint(x: self.size.width + 50 + plane.size.width/3 , y: wavea.size.height + randomPosition2 )
plane.physicsBody = SKPhysicsBody(rectangleOf: planePhysicsSz)
plane.physicsBody?.affectedByGravity = false
plane.physicsBody?.categoryBitMask = PhysicsCategory.plane
plane.physicsBody?.isDynamic = true
plane.physicsBody?.collisionBitMask = PhysicsCategory.bird
plane.physicsBody?.contactTestBitMask = PhysicsCategory.bird
plane.zPosition = 1
jetpair.addChild(plane)
jetpair.run(moveAndRemove)
self.addChild(jetpair)
}
func addjets2(){
jetpair2 = SKNode()
let plane2 = SKSpriteNode(imageNamed: "plane2")
let heighta = self.size.height - wavea.size.height * 2
let planeSz = CGSize(width: plane2.size.width * 6/5 , height: plane2.size.height * 6/5 )
let planePhysicsSz = CGSize(width: plane2.size.width/2 , height: plane2.size.height/4)
// plane2.scale(to: planeSz)
plane2.size = planeSz
let randomPosition3 = CGFloat(arc4random_uniform(150))
let randomPosition4 = CGFloat(arc4random_uniform(UInt32(heighta)))
plane2.position = CGPoint(x: self.size.width + 50 + plane2.size.width/3 + randomPosition3, y: wavea.size.height + randomPosition4 )
plane2.physicsBody = SKPhysicsBody(rectangleOf: planePhysicsSz)
plane2.physicsBody?.affectedByGravity = false
plane2.physicsBody?.categoryBitMask = PhysicsCategory.plane
plane2.physicsBody?.isDynamic = true
plane2.physicsBody?.collisionBitMask = PhysicsCategory.bird
plane2.physicsBody?.contactTestBitMask = PhysicsCategory.bird
plane2.zPosition = 1
jetpair2.addChild(plane2)
jetpair2.run(moveAndRemove2)
self.addChild(jetpair2)
}
func addCloud(){
cloudNode = SKNode()
let cloud = SKSpriteNode(imageNamed: "cloud1")
let cloudImageSz = CGSize(width: cloud.size.width/2 , height:cloud.size.height/2)
let cloudPhysicsSz = CGSize(width: cloud.size.width/4 , height: cloud.size.height/6)
let randomPosition2 = CGFloat(arc4random_uniform(UInt32((Float)(self.size.height/6))))
// cloud.scale(to: cloudImageSz)
cloud.size = cloudImageSz
cloud.position = CGPoint(x: self.size.width + cloud.size.width/2 + randomPosition2 , y: self.size.height - randomPosition2 )
cloud.physicsBody = SKPhysicsBody(rectangleOf: cloudPhysicsSz)
cloud.physicsBody?.affectedByGravity = false
cloud.physicsBody?.isDynamic = true
cloud.physicsBody?.categoryBitMask = PhysicsCategory.cloud
cloud.physicsBody?.collisionBitMask = PhysicsCategory.bird
cloud.physicsBody?.contactTestBitMask = PhysicsCategory.bird
cloud.zPosition = -1
cloudNode.addChild(cloud)
cloudNode.run(moveAndRemoveCloud)
self.addChild(cloudNode)
}
func addCloud2(){
cloudNode2 = SKNode()
let cloud = SKSpriteNode(imageNamed: "cloud2")
let cloudImageSz = CGSize(width: cloud.size.width/2 , height:cloud.size.height/2)
let cloudPhysicsSz = CGSize(width: cloud.size.width/4 , height: cloud.size.height/6)
let randomPosition2 = CGFloat(arc4random_uniform(UInt32((Float)(self.size.height/6))))
let randomPosition3 = CGFloat(arc4random_uniform(UInt32((Float)((self.size.width) * 2))))
cloud.size = cloudImageSz
cloud.position = CGPoint(x: self.size.width + cloud.size.width/2 + randomPosition3 , y: self.size.height - randomPosition2 )
cloud.physicsBody = SKPhysicsBody(rectangleOf: cloudPhysicsSz)
cloud.physicsBody?.affectedByGravity = false
cloud.physicsBody?.isDynamic = true
cloud.physicsBody?.categoryBitMask = PhysicsCategory.cloud
cloud.physicsBody?.collisionBitMask = PhysicsCategory.bird
cloud.physicsBody?.contactTestBitMask = PhysicsCategory.bird
cloud.zPosition = 2
cloudNode2.addChild(cloud)
cloudNode2.run(moveAndRemoveCloud)
self.addChild(cloudNode2)
}
func addCloud3(){
cloudNode3 = SKNode()
let cloud = SKSpriteNode(imageNamed: "cloud3")
let cloudImageSz = CGSize(width: cloud.size.width/2 , height:cloud.size.height/2)
let cloudPhysicsSz = CGSize(width: cloud.size.width/4 , height: cloud.size.height/6)
let randomPosition2 = CGFloat(arc4random_uniform(UInt32((Float)(self.size.height/5))))
let randomPosition3 = CGFloat(arc4random_uniform(UInt32((Float)((self.size.height) * 3))))
cloud.size = cloudImageSz
cloud.position = CGPoint(x: self.size.width + cloud.size.width/2 + randomPosition3 , y: self.size.height - randomPosition2 )
cloud.physicsBody = SKPhysicsBody(rectangleOf: cloudPhysicsSz)
cloud.physicsBody?.affectedByGravity = false
cloud.physicsBody?.isDynamic = true
cloud.physicsBody?.categoryBitMask = PhysicsCategory.cloud
cloud.physicsBody?.collisionBitMask = PhysicsCategory.bird
cloud.physicsBody?.contactTestBitMask = PhysicsCategory.bird
cloud.zPosition = 1
cloudNode3.addChild(cloud)
cloudNode3.run(moveAndRemoveCloud)
self.addChild(cloudNode3)
}
func addShip(){
shipNode = SKNode()
let ship = SKSpriteNode(imageNamed: "ship2")
let shipSz = CGSize(width: ship.size.width * 3/2 , height: ship.size.height * 3/2)
let shipPhysicsSz = CGSize(width: ship.size.width , height: ship.size.height/3)
ship.size = shipSz
ship.position = CGPoint(x:ship.size.width/2 - 250 , y: 95 )
ship.physicsBody = SKPhysicsBody(rectangleOf:shipPhysicsSz)
ship.physicsBody?.affectedByGravity = false
ship.physicsBody?.categoryBitMask = PhysicsCategory.ship
ship.physicsBody?.isDynamic = false
ship.physicsBody?.collisionBitMask = PhysicsCategory.bird
ship.physicsBody?.contactTestBitMask = PhysicsCategory.bird
ship.zPosition = -1
shipNode.addChild(ship)
shipNode.run(moveAndRemoveShip)
self.addChild(shipNode)
}
func addFly(){
flyNode = SKNode()
let fly = SKSpriteNode(imageNamed: "fly2")
let flySz = CGSize(width: fly.size.width/4 , height: fly.size.height/4 )
let flyPhysicsSz = CGSize(width: fly.size.width/5, height: fly.size.height/5)
fly.size = flySz
let heighta = self.size.height - wavea.size.height * 2
let randomPosition2 = CGFloat(arc4random_uniform(UInt32(heighta)))
fly.position = CGPoint(x: self.size.width + 150 , y: wavea.size.height + randomPosition2 )
fly.physicsBody = SKPhysicsBody(rectangleOf:flyPhysicsSz)
fly.physicsBody?.affectedByGravity = false
fly.physicsBody?.categoryBitMask = PhysicsCategory.fly
fly.physicsBody?.isDynamic = true
fly.physicsBody?.collisionBitMask = PhysicsCategory.bird
fly.physicsBody?.contactTestBitMask = PhysicsCategory.bird
fly.zPosition = -1
let moveUp = SKAction.moveBy(x: 0, y: 20, duration: 0.9)
let sequence = SKAction.sequence([moveUp, moveUp.reversed()])
flyNode.run(SKAction.repeatForever(sequence), withKey: "moving")
flyNode.addChild(fly)
flyNode.run(moveAndRemoveFly)
self.addChild(flyNode)
}
func addTree(){
treeNode = SKNode()
let tree = SKSpriteNode(imageNamed: "tree")
let treeSz = CGSize(width: tree.size.width , height: tree.size.height)
let treePhysicsSz = CGSize(width: tree.size.width/10, height: tree.size.height/2)
tree.size = treeSz
tree.zPosition = -3
tree.physicsBody = SKPhysicsBody(rectangleOf:treePhysicsSz)
tree.position = CGPoint(x: tree.size.width/2 + self.size.width , y: 100 )
tree.physicsBody?.categoryBitMask = PhysicsCategory.tree
tree.physicsBody?.collisionBitMask = PhysicsCategory.bird
tree.physicsBody?.contactTestBitMask = PhysicsCategory.bird
tree.physicsBody?.isDynamic = false
tree.physicsBody?.affectedByGravity = false
treeNode.addChild(tree)
treeNode.run(moveAndRemoveTree)
self.addChild(treeNode)
}
func addTreePineapple(){
treeNodePineapple = SKNode()
let treePineapple = SKSpriteNode(imageNamed: "pineappletree")
let treeSz = CGSize(width: treePineapple.size.width/2 , height: treePineapple.size.height/2)
let treePhysicsSz = CGSize(width: treePineapple.size.width/4, height: treePineapple.size.height/4)
treePineapple.size = treeSz
treePineapple.zPosition = 1
treePineapple.physicsBody = SKPhysicsBody(rectangleOf:treePhysicsSz)
let randomPositionPT = CGFloat(arc4random_uniform(250))
treePineapple.position = CGPoint(x: treePineapple.size.width/2 + self.size.width + randomPositionPT, y: 70 )
treePineapple.physicsBody?.categoryBitMask = PhysicsCategory.pineappletree
treePineapple.physicsBody?.collisionBitMask = PhysicsCategory.bird
treePineapple.physicsBody?.contactTestBitMask = PhysicsCategory.bird
treePineapple.physicsBody?.isDynamic = false
treePineapple.physicsBody?.affectedByGravity = false
treeNodePineapple.addChild(treePineapple)
treeNodePineapple.run(moveAndRemoveTree)
self.addChild(treeNodePineapple)
}
func addWavea(){
waveNode = SKNode()
let wave = SKSpriteNode(imageNamed: "wave2")
let waveSz = CGSize(width: wave.size.width, height: wave.size.height)
wave.size = waveSz
wave.zPosition = 3
wave.position = CGPoint(x: (wave.size.width/2) - 50 , y: (wave.size.height/3))
//wave.position = CGPoint(x: wave.size.width/2 + self.size.width , y: 100 )
waveNode.addChild(wave)
waveNode.run(moveAndRemoveWave)
self.addChild(waveNode)
}
func addWaveb(){
waveNode = SKNode()
let wave = SKSpriteNode(imageNamed: "wave2")
let waveSz = CGSize(width: wave.size.width, height: wave.size.height)
wave.size = waveSz
wave.zPosition = 3
wave.position = CGPoint(x: (Int) (wave.size.width/2) * 3 - 55 , y: (Int) (wave.size.height/3))
waveNode.addChild(wave)
waveNode.run(moveAndRemoveWave)
self.addChild(waveNode)
}
func addWavec(){
waveNode = SKNode()
let wave = SKSpriteNode(imageNamed: "wave2")
let waveSz = CGSize(width: wave.size.width, height: wave.size.height)
wave.size = waveSz
wave.zPosition = 3
wave.position = CGPoint(x: (Int) (wave.size.width/2) * 5 - 60 , y: (Int) (wave.size.height/3))
waveNode.addChild(wave)
waveNode.run(moveAndRemoveWave)
self.addChild(waveNode)
}
func addWaved(){
waveNode = SKNode()
let wave = SKSpriteNode(imageNamed: "wave2")
let waveSz = CGSize(width: wave.size.width, height: wave.size.height)
wave.size = waveSz
wave.zPosition = 3
wave.position = CGPoint(x: (Int) (wave.size.width/2) * 7 - 70 , y: (Int) (wave.size.height/3))
waveNode.addChild(wave)
waveNode.run(moveAndRemoveWave)
self.addChild(waveNode)
}
func addWavee(){
waveNode = SKNode()
let wave = SKSpriteNode(imageNamed: "wave2")
let waveSz = CGSize(width: wave.size.width, height: wave.size.height)
wave.size = waveSz
wave.zPosition = 3
wave.position = CGPoint(x: (Int) (wave.size.width/2) * 9 - 30 , y: (Int) (wave.size.height/3))
waveNode.addChild(wave)
waveNode.run(moveAndRemoveWave)
self.addChild(waveNode)
}
func addWavef(){
waveNode = SKNode()
let wave = SKSpriteNode(imageNamed: "wave2")
let waveSz = CGSize(width: wave.size.width, height: wave.size.height)
wave.size = waveSz
wave.zPosition = 3
wave.position = CGPoint(x: (Int) (wave.size.width/2) * 11 - 30 , y: (Int) (wave.size.height/3))
waveNode.addChild(wave)
waveNode.run(moveAndRemoveWave)
self.addChild(waveNode)
}
func addShark() {
sharkNode = SKNode()
shark.removeFromParent()
shark = SKSpriteNode(imageNamed: "shark")
let sharkSz = CGSize(width: shark.size.width , height: shark.size.height)
shark.size = sharkSz
shark.physicsBody?.isDynamic = true
shark.physicsBody?.affectedByGravity = true
shark.position = CGPoint(x: bird.position.x - 100 , y: bird.position.y - 100 )
shark.zPosition = 2
//move and remove shark
let moveShark = SKAction.moveBy(x: 80 , y:90, duration: TimeInterval(0.7 ))
sharkNode.addChild(shark)
sharkNode.run(moveShark)
self.addChild(sharkNode)
birdHitWave = false
}
func addLightning() {
lightning.removeFromParent()
lightning = SKSpriteNode(imageNamed: "lightning")
let lightningSz = CGSize(width: lightning.size.width , height: lightning.size.height)
lightning.size = lightningSz
lightning.physicsBody?.isDynamic = true
lightning.position = CGPoint(x: bird.position.x , y: bird.position.y + 20 )
lightning.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
lightning.physicsBody?.affectedByGravity = true
lightning.zPosition = 3
self.addChild(lightning)
birdHitCloud = false
}
func addFruit() {
fruit.removeFromParent()
if addTreeFruit == true{
fruit = SKSpriteNode(imageNamed: "fruit")
addTreeFruit = false
}else {
fruit = SKSpriteNode(imageNamed: "pineapple")
}
let fruitSz = CGSize(width: fruit.size.width , height: fruit.size.height)
fruit.size = fruitSz
fruit.physicsBody?.isDynamic = true
fruit.position = CGPoint(x: bird.position.x + 5 , y: bird.position.y - 5 )
fruit.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
fruit.physicsBody?.affectedByGravity = true
fruit.zPosition = 3
let spinFruit = SKAction.rotate(byAngle: CGFloat.pi, duration: 0.7)
let spinForeverFruit = SKAction.repeatForever(spinFruit)
let moveFruit = SKAction.moveBy(x: -5 , y: -100, duration: TimeInterval(1))
let moveAndRemoveFruit = SKAction.sequence([moveFruit, SKAction.removeFromParent()])
fruit.run(spinForeverFruit)
fruit.run(moveAndRemoveFruit)
self.addChild(fruit)
birdHitTree = false
birdHitPineappleTree = false
}
func addBoom() {
boom.removeFromParent()
boom = SKSpriteNode(imageNamed: "crash")
let boomSz = CGSize(width: boom.size.width/2 , height: boom.size.height/2)
boom.size = boomSz
boom.physicsBody?.isDynamic = true
boom.position = CGPoint(x: bird.position.x , y: bird.position.y)
boom.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
boom.physicsBody?.affectedByGravity = true
boom.zPosition = 4
let spin = SKAction.rotate(byAngle: CGFloat.pi, duration: 0.7)
let spinForever = SKAction.repeatForever(spin)
let sizeUp = SKAction.scale(by: 5 , duration: 0.7)
boom.run(spinForever)
boom.run(sizeUp)
self.addChild(boom)
birdHitJet = false
}
func addBonus(){
bonus.removeFromSuperview()
bonus = UILabel(frame: CGRect(x: self.size.width/2 - 250, y: self.size.height/2 - 50, width: 500, height: 100))
bonus.textAlignment = .center
bonus.textColor = UIColor.yellow
bonus.font = UIFont.init(name: "MarkerFelt-Thin", size: 30)
if fruitBonusPineapple == true{
bonus.text = "+1000"
fruitBonusPineapple = false
}
else if fruitBonus == true {
bonus.text = "+500"
fruitBonus = false
}
else{
bonus.text = "+50"
}
self.view?.addSubview(bonus)
Timer.scheduledTimer(timeInterval: TimeInterval(0.2), target: self, selector: #selector(GameScene.removeBonuse), userInfo: nil, repeats: false)
}
func removeBonuse(){
bonus.isEnabled = true
bonus.isHidden = true
bonus.removeFromSuperview()
}
func didBegin(_ contact: SKPhysicsContact) {
let firstBody = contact.bodyA
let secondBody = contact.bodyB
if firstBody.categoryBitMask == PhysicsCategory.bird && secondBody.categoryBitMask == PhysicsCategory.plane
||
firstBody.categoryBitMask == PhysicsCategory.plane && secondBody.categoryBitMask == PhysicsCategory.bird
{
birdHitJet = true
}
if firstBody.categoryBitMask == PhysicsCategory.bird && secondBody.categoryBitMask == PhysicsCategory.ship
||
firstBody.categoryBitMask == PhysicsCategory.ship && secondBody.categoryBitMask == PhysicsCategory.bird
{
// birdHitJet = true
bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 2))
}
if firstBody.categoryBitMask == PhysicsCategory.bird && secondBody.categoryBitMask == PhysicsCategory.cloud
||
firstBody.categoryBitMask == PhysicsCategory.cloud && secondBody.categoryBitMask == PhysicsCategory.bird
{
birdHitCloud = true
}
if firstBody.categoryBitMask == PhysicsCategory.bird && secondBody.categoryBitMask == PhysicsCategory.fly
||
firstBody.categoryBitMask == PhysicsCategory.fly && secondBody.categoryBitMask == PhysicsCategory.bird
{
birdHitFly = true
}
if firstBody.categoryBitMask == PhysicsCategory.bird && secondBody.categoryBitMask == PhysicsCategory.tree
||
firstBody.categoryBitMask == PhysicsCategory.tree && secondBody.categoryBitMask == PhysicsCategory.bird
{
birdHitTree = true
}
if firstBody.categoryBitMask == PhysicsCategory.bird && secondBody.categoryBitMask == PhysicsCategory.pineappletree
||
firstBody.categoryBitMask == PhysicsCategory.pineappletree && secondBody.categoryBitMask == PhysicsCategory.bird
{
birdHitPineappleTree = true
}
}
func playlatinHorn() -> AVAudioPlayer {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "intro1", ofType: "wav")!))
audioPlayer?.prepareToPlay()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
return audioPlayer!
}
func playElectric() -> AVAudioPlayer {
do {
playerLight = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sound_electric", ofType: "wav")!))
playerLight?.prepareToPlay()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
return playerLight!
}
func playBubble() -> AVAudioPlayer {
do {
playerBubble = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sharkSound", ofType: "wav")!))
playerBubble?.prepareToPlay()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
return playerBubble!
}
func playBird() -> AVAudioPlayer {
do {
player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sound_bird", ofType: "wav")!))
player?.prepareToPlay()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
return player!
}
func playBoom() -> AVAudioPlayer {
do {
player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "blast", ofType: "wav")!))
player?.prepareToPlay()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
return player!
}
func playIsland() -> AVAudioPlayer {
do {
player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sound_island", ofType: "wav")!))
player?.prepareToPlay()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
return player!
}
func playTree() -> AVAudioPlayer {
do {
player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "coconut", ofType: "wav")!))
player?.prepareToPlay()
}catch let error as NSError {
print("error: \(error.localizedDescription)")
}
return player!
}
func playFly() -> AVAudioPlayer {
do {
player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "fly", ofType: "wav")!))
player?.prepareToPlay()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
return player!
}
func saveHS(number: Int){
if GKLocalPlayer.localPlayer().isAuthenticated{
let scoreReport = GKScore(leaderboardIdentifier: "HS")
scoreReport.value = Int64(number)
let scoreArray: [GKScore] = [scoreReport]
GKScore.report(scoreArray, withCompletionHandler: nil)
}
}
func showGC(){
let VC = self.view?.window?.rootViewController
let GCVC = GKGameCenterViewController()
GCVC.gameCenterDelegate = self
VC?.present(GCVC, animated: true, completion: nil)
let userDefaults = UserDefaults.standard
let highscore7 = userDefaults.value(forKey: "highscore")
saveHS(number: highscore7 as! Int)
}
//shows leaderboard screen
func showLeader() {
let vc = self.view?.window?.rootViewController
let gc = GKGameCenterViewController()
gc.gameCenterDelegate = self
vc?.present(gc, animated: true, completion: nil)
}
//hides leaderboard screen
func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController)
{
gameCenterViewController.dismiss(animated: true, completion: nil)
}
func authPlayer() {
let localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {
(view, error) -> Void in
if view != nil {
let VC = self.view?.window?.rootViewController
VC?.present(view!, animated: true, completion: nil)
}else {
print(GKLocalPlayer.localPlayer().isAuthenticated)
}
}
}
func showFacebook() {
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {
let mySLComposerSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
adBannerView.removeFromSuperview()
screenShot = captureScreen()!
// mySLComposerSheet?.setInitialText("vogel")
mySLComposerSheet?.add(screenShot)
// mySLComposerSheet?.add(URL(string: "http://www.vogelplay.com/")! as URL!)
let VC = self.view?.window?.rootViewController
VC?.present(mySLComposerSheet!, animated: true, completion: nil)
}
else {
let alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
let VC2 = self.view?.window?.rootViewController
VC2?.present(alert, animated: true, completion: nil)
}
}
fileprivate func startNewGame() {
createAndLoadInterstitial()
// Set up a new game.
}
fileprivate func createAndLoadInterstitial() {
interstitial = GADInterstitial(adUnitID: "ca-app-pub-7941365967795667/4059149234")
let request = GADRequest()
request.testDevices = [ kGADSimulatorID ]
interstitial.load(request)
}
func addads1I(){
if interstitial.isReady {
let currentViewController:UIViewController=UIApplication.shared.keyWindow!.rootViewController!
interstitial.present(fromRootViewController: currentViewController)
} else {
print("Ad wasn't ready")
}
}
func banner() {
adBannerView.removeFromSuperview()
adBannerView.adSize = kGADAdSizeSmartBannerLandscape
self.view?.addSubview(adBannerView)
adBannerView.adUnitID = "ca-app-pub-7941365967795667/9898703231"
let currentViewController:UIViewController=UIApplication.shared.keyWindow!.rootViewController!
self.adBannerView.rootViewController = currentViewController
adBannerView.delegate=self
let request2 = GADRequest()
request2.testDevices = [ kGADSimulatorID ]
adBannerView.load(request2)
}
func captureScreen() -> UIImage? {
UIGraphicsBeginImageContextWithOptions((view?.bounds.size)!, true, UIScreen.main.scale)
view?.layer.render(in: UIGraphicsGetCurrentContext()!)
image0 = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image0
}
}
|
mit
|
d260542841aa797284151253e559518e
| 43 | 221 | 0.633826 | 4.261527 | false | false | false | false |
adevelopers/prosvet
|
Prosvet/Common/Controllers/MainVC.swift
|
1
|
2181
|
//
// ViewController.swift
// Prosvet
//
// Created by adeveloper on 17.04.17.
// Copyright © 2017 adeveloper. All rights reserved.
//
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var uiTable: UITableView!
var posts:[Post] = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
loadFeedFromServer()
}
func loadFeedFromServer(){
let model = NetModel()
model.npGetList({
posts in
DispatchQueue.main.async {
self.posts = posts
self.uiTable.reloadData()
}
})
}
}
// MARK: - Constants
extension MainVC {
fileprivate struct Constants {
static let postCellIdentifier = "PostCell"
static let postSegueIdentifier = "segueShowPost"
}
}
//MARK: DataSource
extension MainVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("MainCell", owner: self, options: nil)?.first as! MainCell
let title = posts[indexPath.row].title
cell.uiTitle.text = title
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80.0
}
}
// MARK: - UITableViewDelegate
extension MainVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: Constants.postSegueIdentifier, sender: posts[indexPath.row])
}
}
// MARK: - Segue
extension MainVC {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Constants.postSegueIdentifier {
let controller = segue.destination as! PostDetail
let post = sender as! Post
controller.post = post
}
}
}
|
mit
|
8af4d3d871078f82f57f533a90dc722f
| 22.695652 | 110 | 0.618349 | 4.898876 | false | false | false | false |
aamays/insta-parse
|
InstaParse/ViewControllers/RegistrationViewController.swift
|
1
|
1761
|
//
// RegistrationViewController.swift
// InstaParse
//
// Created by Amay Singhal on 1/23/16.
// Copyright © 2016 CodePath. All rights reserved.
//
import UIKit
import Parse
class RegistrationViewController: UIViewController {
@IBOutlet weak var usernameLabel: UITextField!
@IBOutlet weak var emailLabel: UITextField!
@IBOutlet weak var passwordLabel: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registerUser(sender: UIButton) {
let newUser = PFUser()
newUser.username = usernameLabel.text
newUser.email = emailLabel.text
newUser.password = passwordLabel.text
newUser.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if let error = error {
print(error.localizedDescription)
} else {
print("User Registered successfully")
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
@IBAction func cancelButton(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
0282e0fccedf369800604dc5ed6a34cc
| 28.333333 | 106 | 0.654545 | 5.301205 | false | false | false | false |
Bartlebys/Bartleby
|
Bartleby.xOS/core/Default.swift
|
1
|
9679
|
//
// Default.swift
// Bartleby
//
// Created by Benoit Pereira da Silva on 18/12/2015.
// Copyright © 2015 https://pereira-da-silva.com for Chaosmos SAS
// All rights reserved you can ask for a license.
import Foundation
// MARK: - BartlebyConfiguration
public protocol BartlebyConfiguration {
// The Default base key used to encrypt / decrypt (the metadata)
// We use a different key for the data (saved during the activation process)
static var KEY: String { get }
// This 32Bytes string is used to validate the tokens consistency
// Should be the same server and client side and should not be disclosed
static var SHARED_SALT: String { get }
// To conform to crypto legal context
static var KEY_SIZE: KeySize { get set }
// Collaboration server base URL
// eg : https://demo.bartlebys.org/www/api/v1
static var API_BASE_URL: URL { get set }
static var defaultBaseURLList: [String] { get }
// Bartleby Bprint
static var ENABLE_GLOG: Bool { get set }
// Should Bprint entries be printed
static var PRINT_GLOG_ENTRIES: Bool { get set }
// Use NoCrypto as CryptoDelegate
static var DISABLE_DATA_CRYPTO: Bool { get }
//If set to true the created instances will be remove on maintenance Purge
static var EPHEMERAL_MODE: Bool { get set }
//Should the app try to be online by default
static var ONLINE_BY_DEFAULT: Bool { get set }
// Consignation
static var API_CALL_TRACKING_IS_ENABLED: Bool { get set }
static var BPRINT_API_TRACKED_CALLS: Bool { get set }
// Should we save the password by Default ?
static var SAVE_PASSWORD_BY_DEFAULT: Bool { get set }
// If set to JSON for example would be Indented
static var HUMAN_FORMATTED_SERIALIZATON_FORMAT: Bool { get set }
// The min password size
static var MIN_PASSWORD_SIZE: UInt { get set }
// E.g : Default.DEFAULT_PASSWORD_CHAR_CART
static var PASSWORD_CHAR_CART: String { get set }
// Supervision loop interval (1 second min )
static var LOOP_TIME_INTERVAL_IN_SECONDS: Double { get set }
// To guarantee the sequential Execution use 1 (!)
static var MAX_OPERATIONS_BUNCH_SIZE: Int { get set }
// If set to true the keyed changes are stored in the ManagedModel - When opening the Inspector this default value is remplaced by true
static var CHANGES_ARE_INSPECTABLES_BY_DEFAULT: Bool { get set }
// If set to true the confirmation code will be for example printed in the console...
static var DEVELOPER_MODE: Bool { get }
// If set to true identification will not require second auth factor.
static var SECOND_AUTHENTICATION_FACTOR_IS_DISABLED:Bool { get }
// Supports by default KeyChained password synchronization between multiple local accounts (false is more secured)
static var SUPPORTS_PASSWORD_SYNDICATION_BY_DEFAULT: Bool { get }
// Supports by default the ability to update the password. Recovery procedure for accounts that have allready be saved in the KeyChain (false is more secured)
static var SUPPORTS_PASSWORD_UPDATE_BY_DEFAULT: Bool { get }
// Allows by default users to memorize password (false is more secured)
static var SUPPORTS_PASSWORD_MEMORIZATION_BY_DEFAULT: Bool { get }
// If set to true the user can skip the account creation and stay fully offline.
static var ALLOW_ISOLATED_MODE: Bool { get }
// If set to true each document has it own isolated user
static var AUTO_CREATE_A_USER_AUTOMATICALLY_IN_ISOLATED_MODE: Bool { get }
}
// MARK: - BartlebyDefaultConfiguration
public struct BartlebyDefaultConfiguration: BartlebyConfiguration {
// The Default base key used to encrypt / decrypt (the metadata)
// We use a different key for the data (saved during the activation process)
public static let KEY: String="zHfAKvIb5DexA5hB18Jih92fKyv01niSMU38l8hPRddwduaJ_client"
// This 32Bytes string is used to validate the tokens consistency
// Should be the same server and client side and should not be disclosed
public static let SHARED_SALT: String="rQauWtd9SFheA2koarKhMmHDvKjlB12qOIzVLmvAf7lOH6xdjQlSV9WG4TBYkYxK"
// To conform to crypto legal context
public static var KEY_SIZE: KeySize = .s128bits
// Collaboration server base URL
// This bartlebys default ephemeral demo server (data are erased chronically)
public static var API_BASE_URL: URL = URL(string: "https://demo.bartlebys.org/www/api/v1")!
public static var defaultBaseURLList: [String] {
return ["https://demo.bartlebys.org/www/api/v1"]
}
// Bartleby Bprint
public static var ENABLE_GLOG: Bool=true
// Should Bprint entries be printed
public static var PRINT_GLOG_ENTRIES: Bool=true
// Use NoCrypto as CryptoDelegate (should be false)
public static var DISABLE_DATA_CRYPTO: Bool { return false }
//If set to true the created instances will be remove on maintenance Purge
public static var EPHEMERAL_MODE=true
//Should the app try to be online by default
public static var ONLINE_BY_DEFAULT=true
// Consignation
public static var API_CALL_TRACKING_IS_ENABLED: Bool=true
public static var BPRINT_API_TRACKED_CALLS: Bool=true
// Should we save the password by Default ?
public static var SAVE_PASSWORD_BY_DEFAULT: Bool=false
// If set to JSON for example would be Indented
public static var HUMAN_FORMATTED_SERIALIZATON_FORMAT: Bool=false
// The min password size
public static var MIN_PASSWORD_SIZE: UInt=6
// Supervision loop interval (1 second min )
public static var LOOP_TIME_INTERVAL_IN_SECONDS: Double = 1
// To guarantee the sequential Execution use 1
public static var MAX_OPERATIONS_BUNCH_SIZE: Int=10
// E.g : Default.DEFAULT_PASSWORD_CHAR_CART
public static var PASSWORD_CHAR_CART: String=Default.DEFAULT_PASSWORD_CHAR_CART
// If set to true the keyed changes are stored in the ManagedModel - When opening the Inspector this default value is remplaced by true
public static var CHANGES_ARE_INSPECTABLES_BY_DEFAULT: Bool = false
// If set to true the confirmation code will be for example printed in the console...
public static let DEVELOPER_MODE: Bool = false
// If set to true identification will not required second auth factor.
public static var SECOND_AUTHENTICATION_FACTOR_IS_DISABLED: Bool = false
// Supports by default KeyChained password synchronization between multiple local accounts (false is more secured)
public static let SUPPORTS_PASSWORD_SYNDICATION_BY_DEFAULT: Bool = false
// Supports by default the ability to update the password. Recovery procedure for accounts that have allready be saved in the KeyChain (false is more secured)
public static var SUPPORTS_PASSWORD_UPDATE_BY_DEFAULT: Bool = false
// Allows by default users to memorize password (false is more secured)
public static var SUPPORTS_PASSWORD_MEMORIZATION_BY_DEFAULT: Bool = false
// If set to true the user can skip the account creation and stay fully offline.
public static var ALLOW_ISOLATED_MODE: Bool = false
// If set to true each document has it own isolated user
public static var AUTO_CREATE_A_USER_AUTOMATICALLY_IN_ISOLATED_MODE: Bool = false
}
// MARK: - Default values
public struct Default {
// To prevent Int over flow server side.
static public let MAX_INT: Int = Int(Int32.max)
static public let NO_INT_INDEX: Int = MAX_INT
// Log categories
static public let LOG_DEFAULT: String = "Default"
static public let LOG_WARNING: String = "Warning"
static public let LOG_FAULT: String = "FAULT"
static public let LOG_BSFS: String = "BSFS"
static public let LOG_SECURITY: String = "SECURITY"
static public let LOG_IDENTITY: String = "IDENTITY"
//MARK: UserDefault key/values
static public let SERVER_KEY: String = "user_default_server"
static public let USER_EMAIL_KEY: String = "user_default_email"
static public let USER_PASSWORD_KEY: String = "user_default_password"
//Misc constants
static public let UID_KEY: String = "_id"
static public let TYPE_NAME_KEY: String = "typeName"
static public let VOID_STRING: String = ""
static public let VOID_JSON: String = "{}"
static public let NO_STRING_ERROR: String = "NO_STRING_ERROR"
static public let NOT_OBSERVABLE: String = "NOT_OBSERVABLE"
static public let NO_UID: UID = "NO_UID"
static public let NO_NAME: String = "NO_NAME"
static public let NO_COMMENT: String = "NO_COMMENT"
static public let NO_MESSAGE: String = "NO_MESSAGE"
static public let NO_KEY: String = "NO_KEY"
static public let NO_PATH: String = "NO_PATH"
static public let NO_GEM: String = "NO_GEM"
static public let NO_GROUP: String = "NO_GROUP"
static public let NO_METHOD: String = "NO_METHOD"
static public let NO_DIGEST: String = "NO_DIGEST"
static public let NO_PASSWORD: String = "NO_PASSWORD"
static public let NO_SUGAR: String = "NO_SUGAR"
static public let STRING_ENCODING = String.Encoding.utf8
static public let CATEGORY_DOWNLOADS: String = "downloads" // Used on Downloads
static public let CATEGORY_UPLOADS: String = "uploads" // Used on Uploads
static public let CATEGORY_ASSEMBLIES: String = "assemblies" // Used when mounting a box
// A bunch of char in wich to pick to compose a random password
static public let DEFAULT_PASSWORD_CHAR_CART: String = "123456789ABCDEFGHJKMNPQRSTUVWXYZ"
static public let DESERIALIZATION_HAS_FAILED: String = NSLocalizedString("Deserialization has failed", comment: "Deserialization has failed")
}
|
apache-2.0
|
e5284211759dfea070947804aeb447db
| 40.182979 | 162 | 0.718744 | 3.915049 | false | false | false | false |
pmhicks/Spindle-Player
|
Spindle Player/InfoViewController.swift
|
1
|
2921
|
// Spindle Player
// Copyright (C) 2015 Mike Hicks
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Cocoa
class InfoViewController: NSViewController {
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var formatLabel: NSTextField!
@IBOutlet weak var md5Label: NSTextField!
@IBOutlet weak var patternLabel: NSTextField!
@IBOutlet weak var sampleLabel: NSTextField!
@IBOutlet weak var speedLabel: NSTextField!
@IBOutlet var comment: NSTextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
setLabels()
let center = NSNotificationCenter.defaultCenter()
center.addObserverForName(SpindleConfig.kSongChanged, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self] _ in
if let s = self {
s.setLabels()
}
}
}
private func setLabels() {
if let song = SpindleConfig.sharedInstance.currentSong {
titleLabel.stringValue = song.name
formatLabel.stringValue = song.format
md5Label.stringValue = song.md5
patternLabel.stringValue = "\(song.channelCount) Channels, \(song.patternCount) Patterns"
sampleLabel.stringValue = "\(song.sampleCount) Samples, \(song.instrumentCount) Instruments"
speedLabel.stringValue = "Speed: \(song.initialSpeed) BPM: \(song.initialBPM) Global Volume: \(song.globalVolume)"
comment.string = song.comment
} else {
titleLabel.stringValue = ""
formatLabel.stringValue = ""
md5Label.stringValue = ""
patternLabel.stringValue = ""
sampleLabel.stringValue = ""
speedLabel.stringValue = ""
comment.string = ""
}
}
}
|
mit
|
71c86e7cbdedf1a338c98973f0e2b3ab
| 37.946667 | 130 | 0.662787 | 4.909244 | false | false | false | false |
neycwang/WYCDynamicTextController
|
WYCDynamicTextController/Classes/WYCDynamicTextController.swift
|
1
|
5550
|
//
// WYCDynamicTextController.swift
// Pods
//
// Created by apple on 2017/2/19.
//
//
import UIKit
private enum panGestureState
{
case UPPERLEFT
case LOWERLEFT
case UPPERRIGHT
case LOWERRIGHT
case MIDDLE
case NONE
}
open class WYCDynamicTextController: UIViewController
{
public var textField: UITextField!
private var width, height: CGFloat!
private var gestureState: panGestureState = .NONE
{
didSet
{
stateChanged()
}
}
public var minFrameLength: CGFloat = 16
public var minDist: CGFloat = 14
override open func viewDidLoad()
{
super.viewDidLoad()
width = view.frame.width
height = view.frame.height
textField = UITextField(frame: CGRect(x: 96, y: 96, width: 192, height: 24))
textField.font = .systemFont(ofSize: 24)
textField.returnKeyType = .done
textField.delegate = self
view.addSubview(textField)
let gesture = UIPanGestureRecognizer(target: self, action: #selector(swipe(_:)))
view.addGestureRecognizer(gesture)
}
@objc private func swipe(_ sender: UIPanGestureRecognizer)
{
let loc = sender.location(in: view)
let trans = sender.translation(in: view)
if sender.state == .began && gestureState == .NONE
{
gestureState = whereStarted(loc: loc)
return
}
if sender.state == .ended
{
gestureState = .NONE
return
}
if sender.state == .changed
{
if gestureState == .MIDDLE
{
textField.frame.origin = CGPoint(x: textField.frame.minX + trans.x, y: textField.frame.minY + trans.y)
}
if gestureState == .UPPERLEFT
{
if textField.frame.width - trans.x < minFrameLength || textField.frame.height - trans.y < minFrameLength
{
gestureState = .NONE
}
else
{
textField.frame = CGRect(x: textField.frame.minX + trans.x, y: textField.frame.minY + trans.y, width: textField.frame.width - trans.x, height: textField.frame.height - trans.y)
}
}
if gestureState == .LOWERLEFT
{
if textField.frame.width - trans.x < minFrameLength || textField.frame.height + trans.y < minFrameLength
{
gestureState = .NONE
}
else
{
textField.frame = CGRect(x: textField.frame.minX + trans.x, y: textField.frame.minY, width: textField.frame.width - trans.x, height: textField.frame.height + trans.y)
}
}
if gestureState == .UPPERRIGHT
{
if textField.frame.width + trans.x < minFrameLength || textField.frame.height - trans.y < minFrameLength
{
gestureState = .NONE
}
else
{
textField.frame = CGRect(x: textField.frame.minX, y: textField.frame.minY + trans.y, width: textField.frame.width + trans.x, height: textField.frame.height - trans.y)
}
}
if gestureState == .LOWERRIGHT
{
if textField.frame.width + trans.x < minFrameLength || textField.frame.height + trans.y < minFrameLength
{
gestureState = .NONE
}
else
{
textField.frame = CGRect(x: textField.frame.minX, y: textField.frame.minY, width: textField.frame.width + trans.x, height: textField.frame.height + trans.y)
}
}
sender.setTranslation(CGPoint.zero, in: view)
textField.font = .systemFont(ofSize: textField.frame.height)
return
}
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
let loc = touches.first!.location(in: view)
gestureState = whereStarted(loc: loc)
}
private func whereStarted(loc: CGPoint) -> panGestureState
{
let frame = textField.frame
let upperleft = CGPoint(x: frame.minX, y: frame.minY)
let lowerleft = CGPoint(x: frame.minX, y: frame.maxY)
let upperright = CGPoint(x: frame.maxX, y: frame.minY)
let lowerright = CGPoint(x: frame.maxX, y: frame.maxY)
if distance(a: upperleft, b: loc) < minDist
{
return .UPPERLEFT
}
if distance(a: lowerleft, b: loc) < minDist
{
return .LOWERLEFT
}
if distance(a: upperright, b: loc) < minDist
{
return .UPPERRIGHT
}
if distance(a: lowerright, b: loc) < minDist
{
return .LOWERRIGHT
}
if frame.contains(loc)
{
return .MIDDLE
}
return .NONE
}
private func distance(a: CGPoint, b: CGPoint) -> CGFloat
{
let xDist = a.x - b.x
let yDist = a.y - b.y
return sqrt(xDist * xDist + yDist * yDist)
}
open func stateChanged()
{
}
}
extension WYCDynamicTextController: UITextFieldDelegate
{
public func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
}
|
mit
|
29f331b2db5b427e5e0826049e48af39
| 29.833333 | 196 | 0.537477 | 4.450682 | false | false | false | false |
wanliming11/MurlocAlgorithms
|
Last/Algorithms/队列/Queue/Queue/Queue.swift
|
1
|
2043
|
//
// Created by LexusWan on 30/11/2016.
// Copyright (c) 2016 FlyingPuPu. All rights reserved.
//
import Foundation
/*
FIFO
Features: enqueue, dequeue, count, clear ,traverse, top, isEmpty
*/
public struct Queue<T> {
fileprivate var queueArray: [T?] = [T?]()
var head: Int = 0
public var isOptimized: Bool = false
let optimizedSize: Int = 5
//这两个可以用值运算,而不用函数
//这里判断是否为空,就需要用count,而不是isEmpty, 因为前面的内容是optional
public var sIsEmpty: Bool {
return sCount == 0
}
public var sCount: Int {
return queueArray.count - head
}
mutating public func enqueue(_ element: T) {
queueArray.append(element)
}
// MARK: 注意这个算法默认是O(n),开启了优化参数后,则到达一定阀值后,才进行丢弃操作
// 加上@discardableResult 外部可以不利用返回值
@discardableResult mutating public func dequeue() -> T? {
//没有内容直接返回
if sIsEmpty {
return nil
}
if isOptimized {
//先保存当前的内容
let returnValue = queueArray[head]
//把索引的位置清理
queueArray[head] = nil
head += 1
//容量超过了阀值,并且head到达了整个头的1/4,
guard sCount > optimizedSize, head > (sCount / 4) else {
return queueArray.removeFirst()
}
//丢弃前面为nil的对象
queueArray.removeFirst(head)
head = 0
return returnValue
}
return queueArray.removeFirst()
}
mutating public func clear() {
return queueArray.removeAll()
}
public func traverse() {
for element in queueArray {
print("\(element)")
}
}
@discardableResult public func top() -> T? {
print("\(queueArray.first)")
return sIsEmpty ? queueArray[head] : nil
}
}
|
mit
|
7d33d8d3ad0cb03da64e28774241b442
| 21.705128 | 68 | 0.566347 | 3.892308 | false | false | false | false |
937447974/YJCocoa
|
YJCocoa/Classes/AppFrameworks/UIKit/TableView/YJUITableViewManager.swift
|
1
|
6104
|
//
// YJUITableViewManager.swift
// YJCocoa
//
// HomePage:https://github.com/937447974/YJCocoa
// YJ技术支持群:557445088
//
// Created by 阳君 on 2019/5/22.
// Copyright © 2016-现在 YJCocoa. All rights reserved.
//
import UIKit
/** UITableView管理器*/
@objcMembers
open class YJUITableViewManager: NSObject {
/// header 数据源
public var dataSourceHeader = Array<YJUITableCellObject>()
/// cell 数据源
public var dataSourceCell = Array<Array<YJUITableCellObject>>()
/// cell 第一组数据源
public var dataSourceCellFirst: Array<YJUITableCellObject> {
get {return self.dataSourceCell.first!}
set {
if self.dataSourceCell.count > 0 {
self.dataSourceCell[0] = newValue
} else {
self.dataSourceCell.append(newValue)
}
}
}
weak public private(set) var tableView: UITableView!
private var identifierSet = Set<String>()
private var cacheHeightDict = Dictionary<String, CGFloat>()
public init(tableView: UITableView) {
super.init()
self.dataSourceCellFirst = Array()
self.tableView = tableView
tableView.delegate = self
tableView.dataSource = self
}
}
extension YJUITableViewManager: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return self.dataSourceCell.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section < self.dataSourceCell.count else {
YJLogWarn("error:数组越界; selector:\(#function)")
return 0
}
return self.dataSourceCell[section].count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard indexPath.section < self.dataSourceCell.count && indexPath.row < self.dataSourceCell[indexPath.section].count else {
YJLogWarn("error:数组越界; selector:\(#function)")
return YJUITableViewCell.init(style: .default, reuseIdentifier: "YJUITableViewCell")
}
let co = self.dataSourceCell[indexPath.section][indexPath.row]
co.indexPath = indexPath
return self.dequeueReusableCell(withCellObject: co)
}
private func dequeueReusableCell(withCellObject cellObject: YJUITableCellObject) -> UITableViewCell {
let identifier = cellObject.reuseIdentifier
if !self.identifierSet.contains(identifier) {
self.identifierSet.insert(identifier)
self.tableView.register(cellObject.cellClass, forCellReuseIdentifier: identifier)
}
let cell = self.tableView.dequeueReusableCell(withIdentifier: identifier)!
cell.tableViewManager(self, reloadWith: cellObject)
return cell
}
private func dequeueReusableHeaderFooterView(withCellObject cellObject: YJUITableCellObject) -> UITableViewHeaderFooterView? {
let identifier = cellObject.reuseIdentifier
if !self.identifierSet.contains(identifier) {
self.identifierSet.insert(identifier)
self.tableView.register(cellObject.cellClass, forHeaderFooterViewReuseIdentifier: identifier)
}
let view = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: identifier)
view?.tableViewManager(self, reloadWith: cellObject)
return view
}
}
extension YJUITableViewManager: UITableViewDelegate {
// MARK: cell
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let co = self.cellObject(with: indexPath) else {
YJLogWarn("error:数组越界; selector:\(#function)")
return tableView.rowHeight
}
return self.tableView(tableView, heightFor: co)
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let co = self.cellObject(with: indexPath) {
co.didSelectClosure?(self, co)
}
}
// MARK: header
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let co = self.cellHeaderObject(with: section) else {
return tableView.sectionHeaderHeight
}
return self.tableView(tableView, heightFor: co)
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let co = self.cellHeaderObject(with: section) else {
return nil
}
return self.dequeueReusableHeaderFooterView(withCellObject: co)
}
// MARK: private
private func cellObject(with indexPath: IndexPath) -> YJUITableCellObject? {
guard indexPath.section < self.dataSourceCell.count && indexPath.row < self.dataSourceCell[indexPath.section].count else {
return nil
}
let co = self.dataSourceCell[indexPath.section][indexPath.row]
co.indexPath = indexPath
return co
}
private func cellHeaderObject(with section: Int) -> YJUITableCellObject? {
guard section < self.dataSourceHeader.count else {
return nil
}
let co = self.dataSourceHeader[section]
co.indexPath = IndexPath(row: 0, section: section)
return co
}
private func tableView(_ tableView: UITableView, heightFor cellObject: YJUITableCellObject) -> CGFloat {
if let height = cellObject.height {
return height
}
var height = tableView.rowHeight
if let cellType = cellObject.cellClass as? UITableViewCell.Type {
height = cellType.tableViewManager(self, heightWith: cellObject)
} else if let headerType = cellObject.cellClass as? UITableViewHeaderFooterView.Type {
height = headerType.tableViewManager(self, heightWith: cellObject)
}
return height >= 0 ? height : UITableView.automaticDimension
}
}
|
mit
|
87cc2a194d1385a9dff70464513f1cb4
| 36.459627 | 131 | 0.662577 | 5.176824 | false | false | false | false |
lkzhao/MCollectionView
|
Carthage/Checkouts/YetAnotherAnimationLibrary/Sources/Animatables/SpringAnimatable.swift
|
1
|
2273
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol SpringAnimatable: DecayAnimatable {
var defaultStiffness: Double { get set }
var target: AnimationProperty<Value> { get }
}
// convenience
extension SpringAnimatable {
public func setDefaultStiffness(_ stiffness: Double) {
defaultStiffness = stiffness
}
public func animateTo(_ targetValue: Value,
initialVelocity: Value? = nil,
stiffness: Double? = nil,
damping: Double? = nil,
threshold: Double? = nil,
completionHandler: ((Bool) -> Void)? = nil) {
target.value = targetValue
if let initialVelocity = initialVelocity {
velocity.value = initialVelocity
}
solver = SpringSolver(stiffness: stiffness ?? defaultStiffness,
damping: damping ?? defaultDamping,
threshold: threshold ?? defaultThreshold,
current: value, velocity: velocity, target: target)
start(completionHandler)
}
}
|
mit
|
4b082a90b8b092af3b834a973a7797fb
| 41.886792 | 81 | 0.662121 | 5.107865 | false | false | false | false |
BugMomon/weibo
|
NiceWB/NiceWB/Classes/Main(主要)/Visitor/VisitorView.swift
|
1
|
1309
|
//
// VisitorView.swift
// NiceWB
//
// Created by HongWei on 2017/3/23.
// Copyright © 2017年 HongWei. All rights reserved.
//
import UIKit
class VisitorView: UIView {
//创建个类方法构造xil视图
class func addVisitorView() -> VisitorView{
return Bundle.main.loadNibNamed("VisitorView", owner: nil, options: nil)?.first as! VisitorView
}
// MARK:- 控件属性
@IBOutlet weak var rotationView: UIImageView!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var register: UIButton!
@IBOutlet weak var login: UIButton!
// MARK:- 创建一个给每个视图控制器自定义自己的访客视图
func setupVisitorViewInfo(iconName:String,titleName:String) {
iconView.image = UIImage(named:iconName)
self.tipLabel.text = titleName
rotationView.isHidden = true
}
// MARK:- 创建一个旋转动画
func addRotationAnimation() {
let rotation = CABasicAnimation(keyPath:"transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = M_PI*2
rotation.repeatCount = MAXFLOAT
rotation.isRemovedOnCompletion = false
rotation.duration = 6.0
rotationView.layer.add(rotation, forKey:nil)
}
}
|
apache-2.0
|
345e08ea900621fc33d0741ab19fd0c7
| 27.325581 | 103 | 0.665846 | 4.273684 | false | false | false | false |
findyam/AMScrollingNavbar
|
Source/ScrollingNavbar.swift
|
1
|
12858
|
import UIKit
/**
A custom `UINavigationController` that enables the scrolling of the navigation bar alongside the
scrolling of an observed content view
*/
public class ScrollingNavigationController: UINavigationController, UIGestureRecognizerDelegate {
/**
Returns true if the navbar is fully collapsed
*/
public private(set) var collapsed = false
/**
Returns true if the navbar is fully expanded
*/
public private(set) var expanded = true
/**
Determines wether the scrollbar should scroll when the content inside the scrollview fits
the view's size. Defaults to `false`
*/
public var shouldScrollWhenContentFits = false
/**
Determines if the scrollbar should expand once the application becomes active after entering background
Defaults to `true`
*/
public var expandOnActive = true
var delayDistance: CGFloat = 0
var maxDelay: CGFloat = 0
var gestureRecognizer: UIPanGestureRecognizer?
var scrollableView: UIView?
var lastContentOffset = CGFloat(0.0)
/**
Start scrolling
Enables the scrolling by observing a view
:param: scrollableView The view with the scrolling content that will be observed
:param: delay The delay expressed in points that determines the scrolling resistance. Defaults to `0`
*/
public func followScrollView(scrollableView: UIView, delay: Double = 0) {
self.scrollableView = scrollableView
gestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePan:"))
gestureRecognizer?.maximumNumberOfTouches = 1
gestureRecognizer?.delegate = self
scrollableView.addGestureRecognizer(gestureRecognizer!)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didBecomeActive:"), name: UIApplicationDidBecomeActiveNotification, object: nil)
maxDelay = CGFloat(delay)
delayDistance = CGFloat(delay)
}
/**
Hide the navigation bar
:param: animated If true the scrolling is animated. Defaults to `true`
*/
public func hideNavbar(animated: Bool = true) {
if let scrollableView = self.scrollableView {
if expanded {
UIView.animateWithDuration(animated ? 0.1 : 0, animations: { () -> Void in
self.scrollWithDelta(self.fullNavbarHeight())
self.visibleViewController.view.setNeedsLayout()
if self.navigationBar.translucent {
let currentOffset = self.contentOffset()
self.scrollView()?.contentOffset = CGPoint(x: currentOffset.x, y: currentOffset.y + self.navbarHeight())
}
})
} else {
updateNavbarAlpha()
}
}
}
/**
Show the navigation bar
:param: animated If true the scrolling is animated. Defaults to `true`
*/
public func showNavbar(animated: Bool = true) {
if let scrollableView = self.scrollableView {
if collapsed {
gestureRecognizer?.enabled = false
UIView.animateWithDuration(animated ? 0.1 : 0, animations: { () -> Void in
self.lastContentOffset = 0;
self.delayDistance = -self.fullNavbarHeight()
self.scrollWithDelta(-self.fullNavbarHeight())
self.visibleViewController.view.setNeedsLayout()
if self.navigationBar.translucent {
let currentOffset = self.contentOffset()
self.scrollView()?.contentOffset = CGPoint(x: currentOffset.x, y: currentOffset.y - self.navbarHeight())
}
}) { _ in
gestureRecognizer?.enabled = true
}
} else {
updateNavbarAlpha()
}
}
}
/**
Stop observing the view and reset the navigation bar
*/
public func stopFollowingScrollView() {
showNavbar(animated: false)
if let gesture = gestureRecognizer {
scrollableView?.removeGestureRecognizer(gesture)
}
scrollableView = .None
gestureRecognizer = .None
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
}
// MARK: - Gesture recognizer
func handlePan(gesture: UIPanGestureRecognizer) {
if let scrollableView = scrollableView, let superview = scrollableView.superview {
let translation = gesture.translationInView(superview)
let delta = lastContentOffset - translation.y
lastContentOffset = translation.y
if shouldScrollWithDelta(delta) {
scrollWithDelta(delta)
}
}
if gesture.state == .Ended || gesture.state == .Cancelled {
checkForPartialScroll()
lastContentOffset = 0
}
}
// MARK: - Notification handler
func didBecomeActive(notification: NSNotification) {
if expandOnActive {
showNavbar(animated: false)
}
}
// MARK: - Scrolling functions
func shouldScrollWithDelta(delta: CGFloat) -> Bool {
// Check for rubberbanding
if delta < 0 {
if let scrollableView = scrollableView {
if contentOffset().y + scrollableView.frame.size.height > contentSize().height {
if scrollableView.frame.size.height < contentSize().height {
// Only if the content is big enough
return false
}
}
}
} else {
if contentOffset().y < 0 {
return false
}
}
return true
}
func scrollWithDelta(var delta: CGFloat) {
let frame = navigationBar.frame
// View scrolling up, hide the navbar
if delta > 0 {
// No need to scroll if the content fits
if !shouldScrollWhenContentFits && !collapsed {
if scrollableView?.frame.size.height >= contentSize().height {
return
}
}
expanded = false
// Compute the bar position
if frame.origin.y - delta < -deltaLimit() {
delta = frame.origin.y + deltaLimit()
}
// Detect when the bar is completely collapsed
if frame.origin.y == -deltaLimit() {
collapsed = true
delayDistance = maxDelay
}
}
if delta < 0 {
collapsed = false
// Update the delay
delayDistance += delta
// Skip if the delay is not over yet
if delayDistance > 0 && self.maxDelay < contentOffset().y {
return
}
// Compute the bar position
if frame.origin.y - delta > statusBar() {
delta = frame.origin.y - statusBar()
}
// Detect when the bar is completely expanded
if frame.origin.y == statusBar() {
expanded = true
}
}
updateSizing(delta)
updateNavbarAlpha()
restoreContentOffset(delta)
}
func updateSizing(delta: CGFloat) {
var frame = navigationBar.frame
// Move the navigation bar
frame.origin = CGPoint(x: frame.origin.x, y: frame.origin.y - delta)
navigationBar.frame = frame
// Resize the view if the navigation bar is not translucent
if !navigationBar.translucent {
let navBarY = navigationBar.frame.origin.y + navigationBar.frame.size.height
frame = visibleViewController.view.frame
frame.origin = CGPoint(x: frame.origin.x, y: navBarY)
frame.size = CGSize(width: frame.size.width, height: view.frame.size.height - (navBarY))
visibleViewController.view.frame = frame
}
}
func restoreContentOffset(delta: CGFloat) {
if navigationBar.translucent {
return
}
// Hold the scroll steady until the navbar appears/disappears
let offset = contentOffset()
if let scrollView = scrollView() {
if scrollView.translatesAutoresizingMaskIntoConstraints() {
scrollView.setContentOffset(CGPoint(x: offset.x, y: offset.y - delta), animated: false)
} else {
if delta > 0 {
scrollView.setContentOffset(CGPoint(x: offset.x, y: offset.y - delta - 1), animated: false)
} else {
scrollView.setContentOffset(CGPoint(x: offset.x, y: offset.y - delta + 1), animated: false)
}
}
}
}
func checkForPartialScroll() {
let position = navigationBar.frame.origin.y
var frame = navigationBar.frame
// Scroll back down
if position >= (statusBar() - (frame.size.height / 2)) {
let delta = frame.origin.y - statusBar()
let duration = NSTimeInterval(abs((delta / (frame.size.height / 2)) * 0.2))
UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
self.expanded = true
self.collapsed = false
self.updateSizing(delta)
self.updateNavbarAlpha()
}, completion: nil)
} else {
// Scroll up
let delta = frame.origin.y + deltaLimit()
let duration = NSTimeInterval(abs((delta / (frame.size.height / 2)) * 0.2))
UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
self.expanded = false
self.collapsed = true
self.updateSizing(delta)
self.updateNavbarAlpha()
}, completion: nil)
}
}
func updateNavbarAlpha() {
let frame = navigationBar.frame
// Change the alpha channel of every item on the navbr
let alpha = (frame.origin.y + deltaLimit()) / frame.size.height
// Hide all the possible titles
navigationItem.titleView?.alpha = alpha
navigationBar.tintColor = navigationBar.tintColor.colorWithAlphaComponent(alpha)
if let titleColor = navigationBar.titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor {
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: titleColor.colorWithAlphaComponent(alpha)]
} else {
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blackColor().colorWithAlphaComponent(alpha)]
}
// Hide the left items
visibleViewController.navigationItem.leftBarButtonItem?.customView?.alpha = alpha
if let leftItems = visibleViewController.navigationItem.leftBarButtonItems as? [UIBarButtonItem] {
leftItems.map({ $0.customView?.alpha = alpha })
}
// Hide the right items
visibleViewController.navigationItem.rightBarButtonItem?.customView?.alpha = alpha
if let leftItems = visibleViewController.navigationItem.rightBarButtonItems as? [UIBarButtonItem] {
leftItems.map({ $0.customView?.alpha = alpha })
}
}
func deltaLimit() -> CGFloat {
if UI_USER_INTERFACE_IDIOM() == .Pad || UIScreen.mainScreen().scale == 3 {
return portraitNavbar() - statusBar()
} else {
return (UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) ?
portraitNavbar() - statusBar() :
landscapeNavbar() - statusBar())
}
}
// MARK: - Utilities
func scrollView() -> UIScrollView? {
if let webView = self.scrollableView as? UIWebView {
return webView.scrollView
} else {
return scrollableView as? UIScrollView
}
}
func contentOffset() -> CGPoint {
if let scrollView = scrollView() {
return scrollView.contentOffset
}
return CGPointZero
}
func contentSize() -> CGSize {
if let scrollView = scrollView() {
return scrollView.contentSize
}
return CGSizeZero
}
// MARK: - UIGestureRecognizerDelegate
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return gestureRecognizer == self.gestureRecognizer
}
}
|
mit
|
31d678020549295189f26792d113e442
| 34.916201 | 179 | 0.59566 | 5.563825 | false | false | false | false |
Jerry0523/JWIntent
|
Intent/Intent.swift
|
1
|
3831
|
//
// Intent.swift
//
// Copyright (c) 2015 Jerry Wong
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum IntentError : Error {
case invalidURL(URLString: String?)
case invalidScheme(scheme: String?)
case invalidPath(path: String?)
case unknown(msg: String)
}
/// An atstract type with an executable intention
public protocol Intent {
associatedtype Config
associatedtype Executor
associatedtype Input
associatedtype Output
typealias Intention = (Input?) -> (Output)
static var defaultCtx: IntentCtx<Intention> { get }
var input: Input? { get set }
var config: Config { get set }
var executor: Executor? { get set }
var intention: Intention { get }
var id: String { get }
init(_ id: String, _ intention: @escaping Intention)
func doSubmit(complete: (() -> ())?)
}
public let AnonymousId = ""
public extension Intent {
func submit(complete: (() -> ())? = nil) {
if let interceptor = try? Interceptor(intent: self) {
interceptor.input = self
interceptor.submit {
self.doSubmit(complete: complete)
}
} else {
doSubmit(complete: complete)
}
}
}
public extension Intent {
init(path: String, ctx: IntentCtx<Intention>? = Self.defaultCtx) throws {
try self.init(URLString: (ctx.self?.scheme)! + "://" + path, inputParser: { _ in return nil }, ctx: ctx)
}
init(URLString: String, inputParser: (([String: Any]?) -> Input?), ctx: IntentCtx<Intention>? = Self.defaultCtx) throws {
var url = URL(string: URLString)
if url == nil, let encodedURLString = URLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
url = URL(string: encodedURLString)
}
guard let mURL = url else {
throw IntentError.invalidURL(URLString: URLString)
}
try self.init(URL: mURL, inputParser: inputParser, ctx: ctx)
}
init(URL: URL, inputParser: (([String: Any]?) -> Input?), ctx: IntentCtx<Intention>? = Self.defaultCtx) throws {
do {
let (box, param) = try (ctx ?? Self.defaultCtx).fetch(withURL: URL)
self.init(box.id, box.raw)
self.input = inputParser(param)
} catch {
throw error
}
}
}
public extension Intent where Input == [String: Any] {
init(URLString: String, ctx: IntentCtx<Intention>? = Self.defaultCtx, executor: Executor? = nil) throws {
do {
try self.init(URLString: URLString, inputParser: { $0 }, ctx: ctx)
} catch {
throw error
}
}
}
|
mit
|
6b087a8257102ea7ec4bd70e82f3ed3c
| 29.895161 | 132 | 0.633777 | 4.398393 | false | false | false | false |
malcommac/Flow
|
FlowDemoApp/Login Controller/Cell and Models/Cells.swift
|
1
|
5347
|
//
// Cells.swift
// Flow-iOS
//
// Created by Daniele Margutti on 28/09/2017.
// Copyright © 2017 Flow. All rights reserved.
//
import Foundation
import UIKit
import Flow
/// This is the logo
public class CellLogo: UITableViewCell, DeclarativeCell {
public typealias T = Void
public static var defaultHeight: CGFloat? = 157.0
public func configure(_: Void, path: IndexPath) { }
public override func awakeFromNib() {
super.awakeFromNib()
self.removeMargins()
}
}
public class CellAutosizeText: UITableViewCell, DeclarativeCell {
public typealias T = String
@IBOutlet public var contentLabel: UILabel?
public func configure(_ text: String, path: IndexPath) {
self.contentLabel?.text = text
}
}
public class CellLoginCredential: UITableViewCell, DeclarativeCell, UITextFieldDelegate {
// This define the model received by cell's instances at runtime.
// If your cell does not need of it you can use Void.
public typealias T = LoginCredentialsModel
private var credentials: LoginCredentialsModel?
@IBOutlet public var emailField: UITextField?
@IBOutlet public var passwordField: UITextField?
@IBOutlet public var buttonLogin: UIButton?
@IBOutlet public var buttonForgotCredentials: UIButton?
public static var defaultHeight: CGFloat? = 250
public var onTapLogin: (() -> (Void))? = nil
public var onTapForgotCredentials: (() -> (Void))? = nil
public override func awakeFromNib() {
super.awakeFromNib()
self.emailField?.delegate = self
self.passwordField?.delegate = self
self.buttonLogin?.addTarget(self, action: #selector(didTapLogin), for: .touchUpInside)
self.buttonForgotCredentials?.addTarget(self, action: #selector(didTapForgotCredentials), for: .touchUpInside)
}
@objc public func didTapLogin() {
self.onTapLogin?()
}
@objc public func didTapForgotCredentials() {
self.onTapForgotCredentials?()
}
/// Configure is called everytime the cell needs to be updated.
/// We want to report the state of LoginCredentialsModel instance into login fields.
public func configure(_ credentials: LoginCredentialsModel, path: IndexPath) {
self.credentials = credentials
self.emailField?.text = credentials.email
self.passwordField?.text = credentials.password
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Just update the model with content of the field
let value = (((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string) as String)
if textField == self.emailField {
self.credentials?.email = value
} else if textField == self.passwordField {
self.credentials?.password = value
}
return true
}
}
public class CellRecoverCredentials: UITableViewCell, DeclarativeCell, UITextFieldDelegate {
public typealias T = Void
@IBOutlet public var buttonRecover: UIButton?
@IBOutlet public var emailField: UITextField?
public var onTapRecover: ((String) -> (Void))? = nil
public func configure(_: Void, path: IndexPath) {
self.emailField?.delegate = self
}
public override func awakeFromNib() {
super.awakeFromNib()
self.buttonRecover?.addTarget(self, action: #selector(didTapRecover), for: .touchUpInside)
}
@objc public func didTapRecover() {
self.onTapRecover?(self.emailField?.text ?? "")
}
}
public class CellProfile: UITableViewCell, DeclarativeCell {
public typealias T = UserProfile
public static var defaultHeight: CGFloat? = 100.0
@IBOutlet public var avatarImage: UIImageView?
@IBOutlet public var fullNameLabel: UILabel?
@IBOutlet public var moodLabel: UILabel?
@IBOutlet public var tapToToggleLabel: UILabel?
public func configure(_: UserProfile, path: IndexPath) {
}
}
public class CellAttribute: UITableViewCell, DeclarativeCell {
public typealias T = UserProfileAttribute
@IBOutlet public var attributeKeyLabel: UILabel?
@IBOutlet public var attributeValueLabel: UILabel?
public func configure(_ p: UserProfileAttribute, path: IndexPath) {
self.attributeKeyLabel?.text = p.label
self.attributeValueLabel?.text = p.value
}
}
public class CellFriend: UITableViewCell, DeclarativeCell {
public typealias T = FriendUser
@IBOutlet public var fullNameLabel: UILabel?
@IBOutlet public var avatarImage: UIImageView?
public private(set) var friend: FriendUser?
public func configure(_ friend: FriendUser, path: IndexPath) {
self.friend = friend
self.fullNameLabel?.text = "\(friend.firstName) \(friend.lastName)"
self.avatarImage?.image = friend.avatar
}
}
public class CellLoader: UITableViewCell, DeclarativeCell {
public typealias T = String
@IBOutlet public var container: UIView?
@IBOutlet public var messageLabel: UILabel?
private var spinnerView = JTMaterialSpinner()
public override func awakeFromNib() {
super.awakeFromNib()
spinnerView.circleLayer.lineWidth = 2.0
spinnerView.circleLayer.strokeColor = APP_TINT_COLOR.cgColor
spinnerView.animationDuration = 2.5
}
public func configure(_ text: String, path: IndexPath) {
self.messageLabel?.text = text
spinnerView.frame = self.container!.bounds
self.container?.addSubview(spinnerView)
spinnerView.beginRefreshing()
}
}
|
mit
|
c436f91a7ef7bed8441113dc094324c2
| 28.535912 | 136 | 0.732697 | 4.287089 | false | false | false | false |
gitmalong/lovelySpriteKitHelpers
|
SKDamagableSpriteNode.swift
|
1
|
4580
|
extension NSDate: Comparable { }
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.isEqualToDate(rhs)
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
//
// Damageable.swift
//
import Foundation
import SpriteKit
import UIKit
import AudioToolbox
/**
Protocol & extension that adds "damagable" functionality to a SKNode
- Node gets life points that can be substracted
- onDeath() is triggered when the node "dies"
- Support for nodes that have children. Use it when all of them should be able to get damaged but the life points (of the parent node) should only be substracted once for each damaging event (i.e. when the hero's body parts are all children and both feets are contacted by the same fire)
Usage:
1) Create a class that conforms to DamagableNode for your parent node and a class that conforms to DamageChild for all your parent nodes children
2) If you want to apply damage to a node check if the node conforms to "Damagable" and apply the damage via subtractHealthPoints() or use getAffectedSKNode() to access the parent/master node and do what ever you want
*/
protocol SKDamagable {
/// Subtract health points
func subtractHealthPoints(number:Int)
/// Returns health points
func getHealthPoints() -> Int
/// Returns self if it is the father node, otherwise it should return the parent node
func getAffectedSKNode() -> SKNode
}
protocol SKDamagableChild:SKDamagable {
var parentNode:SKDamageableMaster! { get set }
}
/// Class redirects all damaging events to the parent node
extension SKDamagableChild where Self:SKNode {
/// Substract health points from the parents node call this only when you are sure the same damage event is not called by other children of your parent
func subtractHealthPoints(number: Int) {
parentNode.subtractHealthPoints(number)
}
/// Returns health points of master node
func getHealthPoints() -> Int {
return parentNode.getHealthPoints()
}
/// Returns master node
func getAffectedSKNode() -> SKNode {
return parentNode.getAffectedSKNode()
}
}
class SKDamagableSpriteNode:SKSpriteNode, SKDamagableChild {
var parentNode: SKDamageableMaster!
init(parentNode:SKDamageableMaster, texture:SKTexture) {
self.parentNode = parentNode
super.init(texture: texture, color: UIColor.whiteColor(), size: texture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/* Master node */
protocol SKDamageableMaster: class, SKDamagable {
var healthPoints:Int { get set }
func updateHealthPoints(number:Int) -> Void
func afterUpdateHealthPoints() -> Void
func onDeath() -> Void
}
/* Master node */
extension SKDamageableMaster where Self:SKNode {
func subtractHealthPoints(number:Int) {
updateHealthPoints(healthPoints-number)
}
func updateHealthPoints(number:Int) {
if (number <= 0) {
healthPoints = 0
onDeath()
} else {
healthPoints = number
}
afterUpdateHealthPoints()
}
func getHealthPoints()->Int {
return self.healthPoints
}
func getAffectedSKNode() -> SKNode {
return self as SKNode
}
}
/// Protocol that adds SKDamageEvents to SKDamagable
protocol SKDamagableWithDamageEvents:class, SKDamagable, SKDamagableEventManager {
/// Adds and applies SKDamageEvent and subtracts health of node
func addAndApplyDamageEvent(event: SKDamageEvent) -> Void
}
/// Default implementation for protocol SKDamagableWithDamageEvents
extension SKDamagableWithDamageEvents {
/// Adds and applies SKDamageEvent and subtracts health of node
func addAndApplyDamageEvent(event: SKDamageEvent) -> Void {
event.applied = true
event.appliedTime = NSDate().timeIntervalSince1970
damageEvents.append(event)
self.subtractHealthPoints(event.damagePoints)
print(self.getHealthPoints())
}
}
/// Updates an SKLabelNode with new health points & vibrates
protocol DamageableUserCharacter:SKDamageableMaster, SKDamagableWithDamageEvents {
var healthPointsLabelNode:SKLabelNode { get }
}
extension DamageableUserCharacter {
func afterUpdateHealthPoints() {
healthPointsLabelNode.text = "\(healthPoints)"
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
|
mit
|
70101eb728f8e9e6b32224094e04eeb9
| 27.993671 | 288 | 0.70393 | 4.378585 | false | false | false | false |
montlebalm/Async
|
Async/waterfall.swift
|
1
|
509
|
import Foundation
extension Async {
class func waterfall<O>(
tasks: [([O], (NSError?, O) -> ()) -> ()],
complete: (NSError?, [O]) -> ()
) {
var results: [O] = []
var queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
for task in tasks {
dispatch_sync(queue) {
task(results) { err, result in
results.append(result)
if err != nil || results.count == tasks.count {
complete(err, results)
}
}
}
}
}
}
|
mit
|
25283a4a972398a07e522b397e956d94
| 19.36 | 65 | 0.508841 | 3.688406 | false | false | false | false |
mparrish91/gifRecipes
|
framework/Extension/NSURLComponents+reddift.swift
|
2
|
862
|
//
// NSURLComponents+reddift.swift
// reddift
//
// Created by sonson on 2015/05/06.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
extension URLComponents {
var dictionary: [String:String] {
var parameters: [String:String] = [:]
if #available(macOS 10.10, *) {
if let queryItems = self.queryItems {
for queryItem in queryItems {
#if os(iOS)
parameters[queryItem.name] = queryItem.value
#elseif os(macOS)
if let value = queryItem.value {
parameters[queryItem.name] = value
}
#endif
}
}
} else {
// Fallback on earlier versions
}
return parameters
}
}
|
mit
|
8737d324311797faf690e6cbfabc3208
| 26.741935 | 68 | 0.484884 | 4.914286 | false | false | false | false |
takaaptech/KDIntroView
|
Example/IntroViewDemo/IntroViewDemo/ViewController.swift
|
3
|
2524
|
//
// ViewController.swift
// IntroViewDemo
//
// Created by Kedan Li on 15/7/5.
// Copyright (c) 2015年 TakeFive Interactive. All rights reserved.
//
import UIKit
import KDIntroView
class ViewController: KDIntroViewController {
@IBOutlet var beginButtonView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
beginButtonView.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 200)
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
//setup the introduction view : number of pages : the nib name of each page
setup(["1View","2View","3View","4View","5View"])
view.bringSubviewToFront(beginButtonView)
}
override func moveEverythingAccordingToIndex(index: CGFloat) {
// setting the movement of the color of the background
if index <= view.frame.width * 0.75{
view.backgroundColor = UIColor.whiteColor()
}else if index > view.frame.width * 0.75 && index <= view.frame.width * 1.25{
view.backgroundColor = UIColor(red: 46.0/255, green: 176.0/255, blue: 138.0/255, alpha: 1)
}else if index > view.frame.width * 1.25 && index < view.frame.width * 1.75{
changeBackgroundColor(index, fromColor: UIColor(red: 46.0/255, green: 176.0/255, blue: 138.0/255, alpha: 1), toColor: UIColor(red: 143.0/255, green: 205.0/255, blue: 232.0/255, alpha: 1), fromIndex: view.frame.width * 1.25, toIndex: view.frame.width * 1.75)
}else if index > view.frame.width * 1.75 && index <= view.frame.width * 3.65{
view.backgroundColor = UIColor(red: 143.0/255, green: 205.0/255, blue: 232.0/255, alpha: 1)
}else if index > view.frame.width * 3.65{
view.backgroundColor = UIColor.whiteColor()
}
if index >= view.frame.width * 3.75 && index <= view.frame.width * 4{
println(index - view.frame.width * 3.75)
beginButtonView.transform = CGAffineTransformMake((index - view.frame.width * 3.75) * 2 / 150, 0, 0, (index - view.frame.width * 3.75) * 2 / 150, 0, 160 - (index - view.frame.width * 3.75) * 2)
}else{
beginButtonView.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 160)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
dd8573b3f69369abb6e2ad597c6215d7
| 39.693548 | 269 | 0.616971 | 3.803922 | false | false | false | false |
spitzgoby/Tunits
|
Example/Tests/DateExtensionTraversalTests.swift
|
1
|
6268
|
//
// DateExtensionTraversalTests.swift
// Tunits
//
// Created by Tom on 12/27/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Tunits
import XCTest
class DateExtensionTraversalTests: XCTestCase {
private var dateFormatter : NSDateFormatter = NSDateFormatter();
private let utilities : TimeUnitTestsUtilities = TimeUnitTestsUtilities()
override func setUp() {
self.dateFormatter = NSDateFormatter();
self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
}
// MARK: - Calculating Units Before and After Date
// MARK: Calculating Hour Before And After
func testCalculatingPreviousHour() {
let september29_11_2015 = self.dateFormatter.dateFromString("2015-09-29 11:00:00")!
let september29_10_2015 = self.dateFormatter.dateFromString("2015-09-29 10:00:00")!
XCTAssertEqual(september29_11_2015.hourBefore(), september29_10_2015)
}
func testCalculatingNextHour() {
let september29_11_2015 = self.dateFormatter.dateFromString("2015-09-29 11:00:00")!
let september29_12_2015 = self.dateFormatter.dateFromString("2015-09-29 12:00:00")!
XCTAssertEqual(september29_11_2015.hourAfter(), september29_12_2015)
}
// MARK: Calculating Day Before and After
func testCalculatingNextDay() {
let september29_2015 = self.dateFormatter.dateFromString("2015-09-29 00:00:00")!
let september30_2015 = self.dateFormatter.dateFromString("2015-09-30 00:00:00")!
XCTAssertEqual(september29_2015.dayAfter(), september30_2015)
}
func testCalculatingPreviousDay() {
let september29_2015 = self.dateFormatter.dateFromString("2015-09-29 00:00:00")!
let september28_2015 = self.dateFormatter.dateFromString("2015-09-28 00:00:00")!
XCTAssertEqual(september29_2015.dayBefore(), september28_2015)
}
// MARK: Calculating Week Before and After
func testCalculatingNextWeekWithSundayAsFirstWeekday() {
let september27_2015 = self.dateFormatter.dateFromString("2015-09-27 00:00:00")!
let october4_2015 = self.dateFormatter.dateFromString("2015-10-04 00:00:00")!
TimeUnit.setStaticCalendar(self.utilities.calendarWithSundayAsFirstWeekday())
XCTAssertEqual(september27_2015.weekAfter(), october4_2015)
}
func testCalculatingNextWeekWithMondayAsFirstWeekday() {
let september28_2015 = self.dateFormatter.dateFromString("2015-09-28 00:00:00")!
let october5_2015 = self.dateFormatter.dateFromString("2015-10-05 00:00:00")!
TimeUnit.setStaticCalendar(self.utilities.calendarWithMondayAsFirstWeekday())
XCTAssertEqual(september28_2015.weekAfter(), october5_2015)
}
func testCalculatingPreviousWeekWithSundayAsFirstWeekday() {
let september27_2015 = self.dateFormatter.dateFromString("2015-09-27 00:00:00")!
let september20_2015 = self.dateFormatter.dateFromString("2015-09-20 00:00:00")!
TimeUnit.setStaticCalendar(self.utilities.calendarWithSundayAsFirstWeekday())
XCTAssertEqual(TimeUnit.weekBefore(september27_2015), september20_2015)
}
func testCalculatingPreviousWeekWithMondayAsFirstWeekday() {
let september28_2015 = self.dateFormatter.dateFromString("2015-09-28 00:00:00")!
let september21_2015 = self.dateFormatter.dateFromString("2015-09-21 00:00:00")!
TimeUnit.setStaticCalendar(self.utilities.calendarWithMondayAsFirstWeekday())
XCTAssertEqual(september28_2015.weekBefore(), september21_2015)
}
// MARK: Calculating Month Before and After
func testCalculatingNextMonth() {
let september1_2015 = self.dateFormatter.dateFromString("2015-09-01 00:00:00")!
let october1_2015 = self.dateFormatter.dateFromString("2015-10-01 00:00:00")!
XCTAssertEqual(TimeUnit().monthAfter(september1_2015), october1_2015)
XCTAssertEqual(TimeUnit.monthAfter(september1_2015), october1_2015)
}
func testCalculatingPreviousMonth() {
let september1_2015 = self.dateFormatter.dateFromString("2015-09-01 00:00:00")!
let august1_2015 = self.dateFormatter.dateFromString("2015-08-01 00:00:00")!
XCTAssertEqual(TimeUnit().monthBefore(september1_2015), august1_2015)
XCTAssertEqual(TimeUnit.monthBefore(september1_2015), august1_2015)
}
// MARK: Calculating Year Before and After
func testCalculatingNextYear() {
let _2015 = self.dateFormatter.dateFromString("2015-01-01 00:00:00")!
let _2016 = self.dateFormatter.dateFromString("2016-01-01 00:00:00")!
XCTAssertEqual(TimeUnit().yearAfter(_2015), _2016)
XCTAssertEqual(TimeUnit.yearAfter(_2015), _2016)
}
func testCalculatingPreviousYear() {
let _2015 = self.dateFormatter.dateFromString("2015-01-01 00:00:00")!
let _2014 = self.dateFormatter.dateFromString("2014-01-01 00:00:00")!
XCTAssertEqual(TimeUnit().yearBefore(_2015), _2014)
XCTAssertEqual(TimeUnit.yearBefore(_2015), _2014)
}
}
|
mit
|
594c50528ec1a030ebe3282839570ae6
| 44.744526 | 91 | 0.703526 | 4.211694 | false | true | false | false |
barbaramartina/styling-in-swift
|
Option - CSS/StylingWithCSS/CSS/Validator.swift
|
1
|
1118
|
//
// Validator.swift
// StylingWithCSS
//
// Created by Barbara Rodeker on 28/08/16.
// Copyright © 2016 Barbara Rodeker. All rights reserved.
//
import UIKit
typealias PropertyValidator = Property -> Bool
typealias SelectorValidator = StyleSelector -> Bool
struct Validator {
let propertyValidators: Dictionary<Property,PropertyValidator>
let selectorsValidators: Dictionary<StyleSelector,SelectorValidator>
init() {
propertyValidators = [ .backgroundColor(value: "") : { property in
switch property {
case .backgroundColor(let value):
if let _ = UIColor(hexaAlpha: value) { return true }
default:
break
}
return false
} ]
selectorsValidators = [ .styleElement(name: "", properties: []) : { element in
switch element {
case .styleElement(let value):
return true //TODO
default:
break
}
return false
} ]
}
}
|
gpl-3.0
|
7f823fec1e7f1b31e74f33b78f720855
| 25.595238 | 86 | 0.544315 | 5.195349 | false | false | false | false |
material-motion/material-motion-swift
|
src/interactions/Scalable.swift
|
2
|
1871
|
/*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
/**
Allows a view to be scaled by a gesture recognizer.
Can be initialized with any of the GesturableConfiguration options.
**Affected properties**
- `view.layer.scale`
**Constraints**
CGFloat constraints may be applied to this interaction.
*/
public final class Scalable: Gesturable<UIPinchGestureRecognizer>, Interaction, Togglable, Manipulation {
public func add(to view: UIView,
withRuntime runtime: MotionRuntime,
constraints applyConstraints: ConstraintApplicator<CGFloat>? = nil) {
let reactiveView = runtime.get(view)
guard let gestureRecognizer = dequeueGestureRecognizer(withReactiveView: reactiveView) else {
return
}
let scale = reactiveView.layer.scale
runtime.connect(enabled, to: ReactiveProperty(initialValue: gestureRecognizer.isEnabled) { enabled in
gestureRecognizer.isEnabled = enabled
})
let reactiveGesture = runtime.get(gestureRecognizer)
aggregateState.observe(state: reactiveGesture.state, withRuntime: runtime)
var stream = reactiveGesture.scaled(from: scale)
if let applyConstraints = applyConstraints {
stream = applyConstraints(stream)
}
runtime.connect(stream, to: scale)
}
}
|
apache-2.0
|
a9af26730ee10bd9bcf64193985a40ed
| 32.410714 | 105 | 0.748797 | 4.809769 | false | false | false | false |
jayesh15111988/JKLoginMVVMDemoSwift
|
JKLoginMVVMDemoSwift/User.swift
|
1
|
977
|
//
// User.swift
// JKLoginMVVMDemoSwift
//
// Created by Jayesh Kawli on 10/10/16.
// Copyright © 2016 Jayesh Kawli. All rights reserved.
//
import Foundation
class User: NSObject {
var firstName: String
var lastName : String
var authToken: String
override var debugDescription: String {
return "\(firstName)\n\(lastName)\n\(authToken)\n"
}
override var description: String {
return "\(firstName)\n\(lastName)\n\(authToken)\n"
}
init(dictionary: [String: String]) {
self.firstName = ""
self.lastName = ""
self.authToken = ""
if let firstName = dictionary["first_name"] {
self.firstName = firstName
}
if let lastName = dictionary["last_name"] {
self.lastName = lastName
}
if let authToken = dictionary["auth_token"] {
self.authToken = authToken
}
super.init()
}
}
|
mit
|
bacf440d13e24f6e50b721bd88d20fbc
| 22.238095 | 58 | 0.5625 | 4.477064 | false | false | false | false |
JanGorman/MapleBacon
|
MapleBacon/Core/Cache/Cache.swift
|
1
|
3333
|
//
// Copyright © 2020 Schnaub. All rights reserved.
//
import UIKit
enum CacheError: Error {
case dataConversion
}
final class Cache<T: DataConvertible> where T.Result == T {
typealias CacheCompletion = (Result<CacheResult<T>, Error>) -> Void
var maxCacheAgeSeconds: TimeInterval {
get {
diskCache.maxCacheAgeSeconds
}
set {
diskCache.maxCacheAgeSeconds = newValue
}
}
private let memoryCache: MemoryCache<String, Data>
private let diskCache: DiskCache
init(name: String) {
self.memoryCache = MemoryCache(name: name)
self.diskCache = DiskCache(name: name)
let notifications = [UIApplication.willTerminateNotification, UIApplication.didEnterBackgroundNotification]
notifications.forEach { notification in
NotificationCenter.default.addObserver(self, selector: #selector(cleanDiskOnNotification), name: notification, object: nil)
}
}
func store(value: T, forKey key: String, completion: ((Error?) -> Void)? = nil) {
let safeKey = safeCacheKey(key)
guard let data = value.toData() else {
return
}
memoryCache[safeKey] = data
diskCache.insert(data, forKey: safeKey, completion: completion)
}
func value(forKey key: String, completion: CacheCompletion? = nil) {
let safeKey = safeCacheKey(key)
if let value = memoryCache[safeKey] {
completion?(convertToTargetType(value, type: .memory))
} else {
diskCache.value(forKey: safeKey) { [weak self] result in
guard let self = self else {
return
}
switch result {
case .success(let data):
// Promote to in-memory cache for faster access the next time
self.memoryCache[safeKey] = data
completion?(self.convertToTargetType(data, type: .disk))
case .failure(let error):
completion?(.failure(error))
}
}
}
}
func clear(_ options: CacheClearOptions, completion: ((Error?) -> Void)? = nil) {
if options.contains(.memory) {
memoryCache.clear()
if !options.contains(.disk) {
completion?(nil)
}
}
if options.contains(.disk) {
diskCache.clear(completion)
}
}
func isCached(forKey key: String) throws -> Bool {
let safeKey = safeCacheKey(key)
if memoryCache.isCached(forKey: safeKey) {
return true
}
return try diskCache.isCached(forKey: safeKey)
}
@objc private func cleanDiskOnNotification() {
clear(.disk)
}
}
private extension Cache {
func convertToTargetType(_ data: Data, type: CacheType) -> Result<CacheResult<T>, Error> {
guard let targetType = T.convert(from: data) else {
return .failure(CacheError.dataConversion)
}
return .success(.init(value: targetType, type: type))
}
func safeCacheKey(_ key: String) -> String {
#if canImport(CryptoKit)
if #available(iOS 13.0, *) {
return cryptoSafeCacheKey(key)
}
#endif
return key.components(separatedBy: CharacterSet(charactersIn: "()/")).joined(separator: "-")
}
}
#if canImport(CryptoKit)
import CryptoKit
@available(iOS 13.0, *)
private extension Cache {
func cryptoSafeCacheKey(_ key: String) -> String {
let hash = Insecure.MD5.hash(data: Data(key.utf8))
return hash.compactMap { String.init(format: "%02x", $0) }.joined()
}
}
#endif
|
mit
|
f059749c338013f15acc4388522fb668
| 25.03125 | 129 | 0.658163 | 4.029021 | false | false | false | false |
rokridi/GiphyHub
|
GiphyHub/Source/Core/Gif.swift
|
1
|
3566
|
//
// Gif.swift
// GiphyHub
//
// Created by Mohamed Aymen Landolsi on 27/07/2017.
// Copyright © 2017 Roridi. All rights reserved.
//
import Foundation
import ObjectMapper
public class Gif: Mappable {
public enum GifType: String {
case gif = "gif"
}
public enum GifRating: String {
case Y = "y"
case G = "g"
case PG = "pg"
case PG13 = "pg-13"
case R = "r"
}
var type: GifType?
public var identifier: String?
public var slug: String?
public var url: URL?
public var bitlyGifURL: URL?
public var bitlyURL: URL?
public var embedURL: URL?
public var userName: String?
public var source: URL?
public var rating: GifRating?
public var caption: String?
public var contentURL: URL?
public var sourceTLD: String?
public var sourcePostURL: URL?
public var importDateTime: Date?
public var trendingTime: Date?
public var fixedHeightImage: GifFixed?
public var fixedHeightStillImage: GifImage?
public var fixedHeightDownsampledImage: GifDownsampled?
public var fixedWidthImage: GifFixed?
public var fixedWidthStillImage: GifImage?
public var fixedWidthDownsampledImage: GifDownsampled?
public var fixedHeightSmallImage: GifSmall?
public var fixedHeightSmallStillImage: GifImage?
public var fixedWidthSmallImage: GifSmall?
public var fixedWidthSmallStillImage: GifImage?
public var downsizedImage: GifDownsized?
public var downsizedStillImage: GifImage?
public var downsizedLargeImage: GifDownsized?
public var originalImage: GifOriginal?
public var originalStillImage: GifImage?
required public init?(map: Map) {
}
public func mapping(map: Map) {
type <- (map["type"], EnumTransform<GifType>())
identifier <- map["id"]
slug <- map["slug"]
url <- (map["url"], URLTransform())
bitlyGifURL <- (map["bitly_gif_url"], URLTransform())
bitlyURL <- (map["bitly_url"], URLTransform())
embedURL <- (map["embed_url"], URLTransform())
userName <- map["username"]
source <- (map["source"], URLTransform())
rating <- (map["rating"], EnumTransform<GifRating>())
caption <- map["caption"]
contentURL <- (map["content_url"], URLTransform())
sourceTLD <- map["source_tld"]
sourcePostURL <- (map["source_post_url"], URLTransform())
importDateTime <- (map["import_datetime"], DateTransform())
trendingTime <- (map["trending_datetime"], DateTransform())
fixedHeightImage <- map["images.fixed_height"]
fixedHeightStillImage <- map["images.fixed_height_still"]
fixedHeightDownsampledImage <- map["images.fixed_height_downsampled"]
fixedWidthImage <- map["images.fixed_width"]
fixedWidthStillImage <- map["images.fixed_width_still"]
fixedWidthDownsampledImage <- map["images.fixed_width_downsampled"]
fixedHeightSmallImage <- map["images.fixed_height_small"]
fixedHeightSmallStillImage <- map["images.fixed_height_small_still"]
fixedWidthSmallImage <- map["images.fixed_width_small"]
fixedWidthSmallStillImage <- map["images.fixed_width_small_still"]
downsizedImage <- map["images.downsized"]
downsizedStillImage <- map["images.downsized_still"]
downsizedLargeImage <- map["images.downsized_large"]
originalImage <- map["images.original"]
originalStillImage <- map["images.original_still"]
}
}
|
mit
|
3a146856fb6cf86892a3128c5fff4170
| 35.752577 | 77 | 0.655259 | 4.269461 | false | false | false | false |
arvedviehweger/swift
|
test/IDE/local_types.swift
|
3
|
4244
|
// Tests lookup and mangling of local types
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swiftc_driver -swift-version 3 -v -emit-module -module-name LocalTypes -o %t/LocalTypes.swiftmodule %s
// RUN: %target-swift-ide-test -swift-version 3 -print-local-types -I %t -module-to-print LocalTypes -source-filename %s | %FileCheck %s
public func singleFunc() {
// CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD6StructL_V
struct SingleFuncStruct {
let sfsi: Int
}
// CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD5ClassL_C
class SingleFuncClass {
let sfcs: String
init(s: String) {
self.sfcs = s
}
}
// CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD4EnumL_O
enum SingleFuncEnum {
case SFEI(Int)
}
}
public func singleFuncWithDuplicates(_ fake: Bool) {
if fake {
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD6StructL_V
struct SingleFuncStruct {
let sfsi: Int
}
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD5ClassL_C
class SingleFuncClass {
let sfcs: String
init(s: String) {
self.sfcs = s
}
}
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD4EnumL_O
enum SingleFuncEnum {
case SFEI(Int)
}
} else {
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD6StructL0_V
struct SingleFuncStruct {
let sfsi: Int
}
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD5ClassL0_C
class SingleFuncClass {
let sfcs: String
init(s: String) {
self.sfcs = s
}
}
// CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD4EnumL0_O
enum SingleFuncEnum {
case SFEI(Int)
}
}
}
public let singleClosure: () -> () = {
// CHECK-DAG: 10LocalTypesyycfU_19SingleClosureStructL_V
struct SingleClosureStruct {
let scsi: Int
}
// CHECK-DAG: 10LocalTypesyycfU_18SingleClosureClassL_C
class SingleClosureClass {
let sccs: String
init(s: String) {
self.sccs = s
}
}
// CHECK-DAG: 10LocalTypesyycfU_17SingleClosureEnumL_O
enum SingleClosureEnum {
case SCEI(Int)
}
}
public var singlePattern: Int {
// CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD6StructL_V
struct SinglePatternStruct {
let spsi: Int
}
// CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD5ClassL_C
class SinglePatternClass {
let spcs: String
init(s: String) {
self.spcs = s
}
}
// CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD4EnumL_O
enum SinglePatternEnum {
case SPEI(Int)
}
return 2
}
public func singleDefaultArgument(i: Int = {
//CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE6StructL_V
struct SingleDefaultArgumentStruct {
let sdasi: Int
}
// CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE5ClassL_C
class SingleDefaultArgumentClass {
let sdacs: String
init(s: String) {
self.sdacs = s
}
}
// CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE4EnumL_O
enum SingleDefaultArgumentEnum {
case SDAEI(Int)
}
return 2
}()){
print(i)
}
public func doubleFunc() {
func innerFunc() {
// CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD6StructL_V
struct DoubleFuncStruct {
let dfsi: Int
}
// CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD5ClassL_C
class DoubleFuncClass {
let dfcs: String
init(s: String) {
self.dfcs = s
}
}
// CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD4EnumL_O
enum DoubleFuncEnum {
case DFEI(Int)
}
}
innerFunc()
}
public let doubleClosure: () -> () = {
let singleClosure: () -> () = {
// CHECK-DAG: 10LocalTypesyycfU0_yycfU_19DoubleClosureStructL_V
struct DoubleClosureStruct {
let dcsi: Int
}
// CHECK-DAG: 10LocalTypesyycfU0_yycfU_18DoubleClosureClassL_C
class DoubleClosureClass {
let dccs: String
init(s: String) {
self.dccs = s
}
}
// CHECK-DAG: 10LocalTypesyycfU0_yycfU_17DoubleClosureEnumL_O
enum DoubleClosureEnum {
case DCEI(Int)
}
}
singleClosure()
}
|
apache-2.0
|
8bb33d12ff879eda66aee20427d055a5
| 25.360248 | 136 | 0.690858 | 3.581435 | false | false | false | false |
dongdonggaui/BiblioArchiver
|
Pods/Fuzi/Sources/Document.swift
|
1
|
6822
|
// Document.swift
// Copyright (c) 2015 Ce Zheng
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import libxml2
/// XML document which can be searched and queried.
open class XMLDocument {
// MARK: - Document Attributes
/// The XML version.
open fileprivate(set) lazy var version: String? = {
return ^-^self.cDocument.pointee.version
}()
/// The string encoding for the document. This is NSUTF8StringEncoding if no encoding is set, or it cannot be calculated.
open fileprivate(set) lazy var encoding: String.Encoding = {
if let encodingName = ^-^self.cDocument.pointee.encoding {
let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString?)
if encoding != kCFStringEncodingInvalidId {
return String.Encoding(rawValue: UInt(CFStringConvertEncodingToNSStringEncoding(encoding)))
}
}
return String.Encoding.utf8
}()
// MARK: - Accessing the Root Element
/// The root element of the document.
open fileprivate(set) var root: XMLElement?
// MARK: - Accessing & Setting Document Formatters
/// The formatter used to determine `numberValue` for elements in the document. By default, this is an `NSNumberFormatter` instance with `NSNumberFormatterDecimalStyle`.
open lazy var numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
/// The formatter used to determine `dateValue` for elements in the document. By default, this is an `NSDateFormatter` instance configured to accept ISO 8601 formatted timestamps.
open lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
// MARK: - Creating XML Documents
fileprivate let cDocument: xmlDocPtr
/**
Creates and returns an instance of XMLDocument from an XML string, throwing XMLError if an error occured while parsing the XML.
- parameter string: The XML string.
- parameter encoding: The string encoding.
- throws: `XMLError` instance if an error occurred
- returns: An `XMLDocument` with the contents of the specified XML string.
*/
public convenience init(string: String, encoding: String.Encoding = String.Encoding.utf8) throws {
guard let cChars = string.cString(using: encoding) else {
throw XMLError.invalidData
}
try self.init(cChars: cChars)
}
/**
Creates and returns an instance of XMLDocument from XML data, throwing XMLError if an error occured while parsing the XML.
- parameter data: The XML data.
- throws: `XMLError` instance if an error occurred
- returns: An `XMLDocument` with the contents of the specified XML string.
*/
public convenience init(data: Data) throws {
let cChars = data.withUnsafeBytes { (bytes: UnsafePointer<Int8>) -> [CChar] in
let buffer = UnsafeBufferPointer(start: bytes, count: data.count)
return [CChar](buffer)
}
try self.init(cChars: cChars)
}
/**
Creates and returns an instance of XMLDocument from C char array, throwing XMLError if an error occured while parsing the XML.
- parameter cChars: cChars The XML data as C char array
- throws: `XMLError` instance if an error occurred
- returns: An `XMLDocument` with the contents of the specified XML string.
*/
public convenience init(cChars: [CChar]) throws {
let options = Int32(XML_PARSE_NOWARNING.rawValue | XML_PARSE_NOERROR.rawValue | XML_PARSE_RECOVER.rawValue)
try self.init(cChars: cChars, options: options)
}
fileprivate convenience init(cChars: [CChar], options: Int32) throws {
guard let document = type(of: self).parse(cChars: cChars, size: cChars.count, options: options) else {
throw XMLError.lastError(defaultError: .parserFailure)
}
xmlResetLastError()
self.init(cDocument: document)
}
fileprivate class func parse(cChars: [CChar], size: Int, options: Int32) -> xmlDocPtr? {
return xmlReadMemory(UnsafePointer(cChars), Int32(size), "", nil, options)
}
fileprivate init(cDocument: xmlDocPtr) {
self.cDocument = cDocument
if let cRoot = xmlDocGetRootElement(cDocument) {
root = XMLElement(cNode: cRoot, document: self)
}
}
deinit {
xmlFreeDoc(cDocument)
}
// MARK: - XML Namespaces
var defaultNamespaces = [String: String]()
/**
Define a prefix for a default namespace.
- parameter prefix: The prefix name
- parameter ns: The default namespace URI that declared in XML Document
*/
open func definePrefix(_ prefix: String, defaultNamespace ns: String) {
defaultNamespaces[ns] = prefix
}
}
extension XMLDocument: Equatable {}
/**
Determine whether two documents are the same
- parameter lhs: XMLDocument on the left
- parameter rhs: XMLDocument on the right
- returns: whether lhs and rhs are equal
*/
public func ==(lhs: XMLDocument, rhs: XMLDocument) -> Bool {
return lhs.cDocument == rhs.cDocument
}
/// HTML document which can be searched and queried.
open class HTMLDocument: XMLDocument {
// MARK: - Convenience Accessors
/// HTML title of current document
open var title: String? {
return root?.firstChild(tag: "head")?.firstChild(tag: "title")?.stringValue
}
/// HTML head element of current document
open var head: XMLElement? {
return root?.firstChild(tag: "head")
}
/// HTML body element of current document
open var body: XMLElement? {
return root?.firstChild(tag: "body")
}
fileprivate override class func parse(cChars: [CChar], size: Int, options: Int32) -> xmlDocPtr? {
return htmlReadMemory(UnsafePointer(cChars), Int32(size), "", nil, options)
}
}
|
mit
|
4fc88ad552bc239b2f771191bb8e8840
| 35.095238 | 181 | 0.716945 | 4.364683 | false | false | false | false |
quadro5/swift3_L
|
swift_question.playground/Pages/Let10 Regualr Expression Matching.xcplaygroundpage/Contents.swift
|
1
|
1441
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
class Solution {
func isMatch(_ s: String, _ p: String) -> Bool {
if s.isEmpty, p.isEmpty{
return true
}
let base = String(".*").utf8.map { Int($0) }
let ss = s.utf8.map { Int($0) }
let pp = p.utf8.map { Int($0) }
let slen = ss.count
let plen = pp.count
// dp[slen][plen]
var dp = Array<Array<Bool>>(
repeating: Array<Bool>(repeating: false, count: plen+1), count: slen+1)
dp[0][0] = true
var i = 0 // aa VS a*, we need true
while i < slen + 1 {
var j = 1
while j < plen + 1 {
// for "*"
if pp[j-1] == base[1] {
// a VS aa*, a* repeat 0, so we use i and j-2
// aaaa VS aa*, a* repeat > 0, so we test i-1(prev) to j(current)
dp[i][j] = dp[i][j-2]
|| (i > 0 && dp[i-1][j] && (ss[i-1] == pp[j-2] || pp[j-2] == base[0]))
// for normal letters and "."
} else {
dp[i][j] = i > 0 && dp[i-1][j-1]
&& (ss[i-1] == pp[j-1] || pp[j-1] == base[0])
}
j += 1
}
i += 1
}
return dp[slen][plen]
}
}
let res = Solution().isMatch("a", "a")
|
unlicense
|
3d80829c13566a0fbd23f782832ffb9f
| 29.659574 | 94 | 0.389313 | 3.275 | false | false | false | false |
Xiomara7/Apps
|
Apps/App.swift
|
1
|
1035
|
//
// App.swift
// Apps
//
// Created by Xiomara on 2/9/17.
// Copyright © 2017 Xiomara. All rights reserved.
//
import UIKit
import SwiftyJSON
typealias AppArray = [App]
class App {
var name: String
var summary: String
var imageURL: String
var category: String
init?(json: JSON) {
guard let name = json[keyName]["label"].string else {
return nil
}
self.name = name
guard let imageURL = json[keyImage].array?.first?["label"].string else {
return nil
}
self.imageURL = imageURL
guard let summary = json[keySummary]["label"].string else {
return nil
}
self.summary = summary
guard let category = json[keyCategory]["label"].string else {
return nil
}
self.category = category
}
}
extension App: Equatable { }
func ==(lhs: App, rhs: App) -> Bool {
return lhs.name == rhs.name
}
|
mit
|
d36d92ac7996640adda2e8256edd411b
| 18.148148 | 80 | 0.530948 | 4.344538 | false | false | false | false |
icanzilb/EventBlankApp
|
EventBlank/EventBlank/ViewControllers/Schedule/Sessions/SessionsViewController.swift
|
2
|
3846
|
//
// SessionsViewController.swift
// EventBlank
//
// Created by Marin Todorov on 6/20/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
import SQLite
import XLPagerTabStrip
class SessionsViewController: UIViewController, XLPagerTabStripChildItem, UITableViewDataSource, UITableViewDelegate {
var day: ScheduleDay! //set from container VC
var items = [ScheduleDaySection]()
var delegate: SessionViewControllerDelegate! //set from previous VC
let schedule = Schedule()
var event: Row {
return (UIApplication.sharedApplication().delegate as! AppDelegate).event
}
var currentSectionIndex: Int? = nil
var lastSelectedSession: Row?
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
backgroundQueue(loadItems, completion: self.tableView.reloadData)
observeNotification(kFavoritesToggledNotification, selector: "didToggleFavorites")
observeNotification(kFavoritesChangedNotification, selector: "didChangeFavorites")
observeNotification(kScrollToCurrentSessionNotification, selector: "scrollToCurrentSession:")
//observeNotification(kDidReplaceEventFileNotification, selector: "didChangeEventFile")
}
deinit {
observeNotification(kFavoritesToggledNotification, selector: nil)
observeNotification(kFavoritesChangedNotification, selector: nil)
observeNotification(kScrollToCurrentSessionNotification, selector: nil)
//observeNotification(kDidReplaceEventFileNotification, selector: nil)
}
func loadItems() {
//build schedule sections
schedule.refreshFavorites()
items = schedule.sessionsByStartTime(day, onlyFavorites: delegate.isFavoritesFilterOn())
mainQueue({
//show no sessions message
if self.items.count == 0 {
self.tableView.addSubview(MessageView(text: "No sessions match your current filter"))
} else {
MessageView.removeViewFrom(self.tableView)
}
})
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let detailsVC = segue.destinationViewController as? SessionDetailsViewController {
detailsVC.session = lastSelectedSession
}
}
// MARK: - XLPagerTabStripChildItem
func titleForPagerTabStripViewController(pagerTabStripViewController: XLPagerTabStripViewController!) -> String! {
return self.title
}
// MARK: - notifications
func didToggleFavorites() {
backgroundQueue(loadItems, completion: self.tableView.reloadData)
}
func didChangeFavorites() {
backgroundQueue(loadItems, completion: self.tableView.reloadData)
}
func didChangeEventFile() {
backgroundQueue(loadItems, completion: self.tableView.reloadData)
}
func scrollToCurrentSession(n: NSNotification) {
if let dayName = n.userInfo?.values.first as? String where dayName == day.text {
let now = Int(NSDate().timeIntervalSince1970)
for index in 0 ..< items.count {
if now < items[index].values.first!.first![Session.beginTime] {
mainQueue({
if self.items.count > 0 {
self.tableView.scrollToRowAtIndexPath(
NSIndexPath(forRow: 0, inSection: index),
atScrollPosition: UITableViewScrollPosition.Top,
animated: true)
}
})
return
}
}
}
}
}
|
mit
|
c384f3003f8a8cbc202e5baafed5bc26
| 33.648649 | 118 | 0.633125 | 5.689349 | false | false | false | false |
Landan/JSONWebToken.swift
|
Sources/Claims.swift
|
1
|
2077
|
import Foundation
func validateClaims(payload:Payload, audience:String?, issuer:String?) -> InvalidToken? {
return validateIssuer(payload: payload, issuer: issuer) ?? validateAudience(payload: payload, audience: audience) ??
validateDate(payload: payload, key: "exp", comparison: .orderedAscending, failure: .ExpiredSignature, decodeError: "Expiration time claim (exp) must be an integer") ??
validateDate(payload: payload, key: "nbf", comparison: .orderedDescending, failure: .ImmatureSignature, decodeError: "Not before claim (nbf) must be an integer") ??
validateDate(payload: payload, key: "iat", comparison: .orderedDescending, failure: .InvalidIssuedAt, decodeError: "Issued at claim (iat) must be an integer")
}
func validateAudience(payload:Payload, audience:String?) -> InvalidToken? {
if let audience = audience {
if let aud = payload["aud"] as? [String] {
if !aud.contains(audience) {
return .InvalidAudience
}
} else if let aud = payload["aud"] as? String {
if aud != audience {
return .InvalidAudience
}
} else {
return .DecodeError("Invalid audience claim, must be a string or an array of strings")
}
}
return nil
}
func validateIssuer(payload:Payload, issuer:String?) -> InvalidToken? {
if let issuer = issuer {
if let iss = payload["iss"] as? String {
if iss != issuer {
return .InvalidIssuer
}
} else {
return .InvalidIssuer
}
}
return nil
}
func validateDate(payload:Payload, key:String, comparison:NSComparisonResult, failure:InvalidToken, decodeError:String) -> InvalidToken? {
if let timestamp: NSTimeInterval = payload[key].double {
let date = NSDate(timeIntervalSince1970: timestamp)
if date.compare(NSDate()) == comparison {
return failure
}
} else if payload[key] != nil {
return .DecodeError(decodeError)
}
return nil
}
|
bsd-2-clause
|
391a35da5ee8d9517349d6268f04540b
| 38.188679 | 175 | 0.631199 | 4.457082 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Card/CardRouter.swift
|
1
|
4081
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import FeatureCardPaymentDomain
import RIBs
import RxRelay
import RxSwift
import ToolKit
public final class CardRouter: RIBs.Router<CardRouterInteractor> {
// MARK: - Types
// MARK: - Private Properties
private let routingType: RoutingType
private let navigationRouter: NavigationRouterAPI
private let builder: CardComponentBuilderAPI
private let disposeBag = DisposeBag()
public init(
interactor: CardRouterInteractor,
builder: CardComponentBuilderAPI,
routingType: RoutingType = .modal,
navigationRouter: NavigationRouterAPI = NavigationRouter()
) {
self.builder = builder
self.navigationRouter = navigationRouter
self.routingType = routingType
super.init(interactor: interactor)
}
// MARK: - Lifecycle
override public func didLoad() {
super.didLoad()
// Embed the entire flow in another navigation controller
// instead of generating one of its own
if case .embed(inside: let navigationController) = routingType {
navigationRouter.navigationControllerAPI = navigationController
}
// Action is a steam of events derived from a pblish relay
interactor.action
.observe(on: MainScheduler.instance)
.bindAndCatch(weak: self) { (self, action) in
switch action {
case .previous(from: let state):
self.previous(from: state)
case .next(to: let state):
self.next(to: state)
}
}
.disposed(by: disposeBag)
// called by `Router` once `self` is attached as a child router.
interactor.activate()
// Once the interator becomes inactive dismiss the flow
interactor.isActiveStream
.filter { !$0 }
.mapToVoid()
.take(1)
.observe(on: MainScheduler.instance)
.bindAndCatch(weak: self) { (self) in
self.navigationRouter.dismiss(completion: nil)
}
.disposed(by: disposeBag)
}
// MARK: - State Routing
private func previous(from state: CardRouterInteractor.State) {
switch state {
case .cardDetails:
interactor.deactivate()
case .authorization, .billingAddress, .completed, .inactive, .pendingCardState:
navigationRouter.pop(animated: true)
}
}
private func next(to state: CardRouterInteractor.State) {
switch state {
case .cardDetails:
showCardDetailsScreen()
case .billingAddress(let cardData):
showBillingAddressScreen(for: cardData)
case .authorization(let data):
showAuthorizationScreen(for: data)
case .pendingCardState(cardId: let cardId):
showPendingCardStateScreen(for: cardId)
case .completed, .inactive:
interactor.deactivate()
}
}
// MARK: - Accessors
private func showPendingCardStateScreen(for cardId: String) {
let viewController = builder.pendingCardStatus(cardId: cardId)
navigationRouter.present(viewController: viewController)
}
private func showAuthorizationScreen(for data: PartnerAuthorizationData) {
guard let viewController = builder.cardAuthorization(for: data) else {
return
}
navigationRouter.present(viewController: viewController)
}
private func showCardDetailsScreen() {
let viewController = builder.cardDetails()
viewController.isModalInPresentation = true
navigationRouter.present(viewController: viewController)
}
private func showBillingAddressScreen(for cardData: CardData) {
let viewController = builder.billingAddress(
for: cardData,
navigationControllerAPI: navigationRouter.navigationControllerAPI!
)
navigationRouter.present(viewController: viewController)
}
}
|
lgpl-3.0
|
d829c9c851d436b2aba89b5f2f6aaa05
| 31.64 | 87 | 0.639951 | 5.244216 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/BlockchainComponentLibrary/Tests/BlockchainComponentLibraryTests/Utilities/View+IfTests.swift
|
1
|
2462
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import SnapshotTesting
import SwiftUI
import XCTest
final class ViewIfTests: XCTestCase {
let view = Rectangle()
override func setUp() {
super.setUp()
isRecording = false
}
func testIfThen() {
let trueResult = view.if(true) { $0.fill(Color.green) }
assertSnapshot(matching: trueResult.fixedSize(), as: .image)
let falseResult = view.if(false) { $0.fill(Color.green) }
assertSnapshot(matching: falseResult.fixedSize(), as: .image)
}
func testIfThenElse() {
let trueResult = view.if(true) { $0.fill(Color.green) } else: { $0.fill(Color.red) }
assertSnapshot(matching: trueResult.fixedSize(), as: .image)
let falseResult = view.if(false) { $0.fill(Color.green) } else: { $0.fill(Color.red) }
assertSnapshot(matching: falseResult.fixedSize(), as: .image)
}
func testIfLetThen() {
let someOptional: String? = "t"
let someResult = view.ifLet(someOptional) { view, value in
view.fill(Color.green)
.overlay(Text(value).typography(.micro))
}
assertSnapshot(matching: someResult.fixedSize(), as: .image)
let nilOptional: String? = nil
let nilResult = view.ifLet(nilOptional) { view, value in
view.fill(Color.green)
.overlay(Text(value).typography(.micro))
}
assertSnapshot(matching: nilResult.fixedSize(), as: .image)
}
func testIfLetThenElse() {
let someOptional: String? = "t"
let someResult = view
.ifLet(
someOptional,
then: { view, value in
view.fill(Color.green)
.overlay(Text(value).typography(.micro))
},
else: { view in
view.fill(Color.red)
}
)
assertSnapshot(matching: someResult.fixedSize(), as: .image)
let nilOptional: String? = nil
let nilResult = view.ifLet(
nilOptional,
then: { view, value in
view.fill(Color.green)
.overlay(Text(value).typography(.micro))
},
else: { view in
view.fill(Color.red)
}
)
assertSnapshot(matching: nilResult.fixedSize(), as: .image)
}
}
|
lgpl-3.0
|
ffcd85038063f5ecbf576e785a827fb8
| 30.961039 | 94 | 0.56156 | 4.221269 | false | true | false | false |
jmfieldman/Mortar
|
Examples/MortarVFL/MortarVFL/Examples/VFL_Example2ViewController.swift
|
1
|
994
|
//
// VFL_Example2ViewController.swift
// MortarVFL
//
// Created by Jason Fieldman on 4/8/17.
// Copyright © 2017 Jason Fieldman. All rights reserved.
//
import Foundation
import UIKit
class VFL_Example2ViewController: UIViewController {
let v1 = UIView.m_create {
$0.backgroundColor = .red
}
let v2 = UIView.m_create {
$0.backgroundColor = .blue
}
let v3 = UIView.m_create {
$0.backgroundColor = .green
}
override func viewDidLoad() {
self.view.backgroundColor = .white
self.view |^| [v1, v2, v3]
self.view |>> 40 | v1 | 40
self.view |>> ~~1 | v2[==40] | ~~2
self.view ||>> v3
self.m_visibleRegion |^^ v1[~~1] | v2[~~1] | v3[~~1]
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
print("\(self.v1.frame)")
print("\(self.v2.frame)")
print("\(self.v3.frame)")
}
}
}
|
mit
|
aa2c376eb051c5a41b528ef1ce160803
| 21.568182 | 61 | 0.517623 | 3.521277 | false | false | false | false |
wikimedia/apps-ios-wikipedia
|
Wikipedia/Code/WMFWelcomeAnimationView.swift
|
1
|
2901
|
import Foundation
open class WMFWelcomeAnimationView : UIView {
// Reminder - these transforms are on WMFWelcomeAnimationView
// so they can scale proportionally to the view size.
private var wmf_proportionalHorizontalOffset: CGFloat{
return CGFloat(0.35).wmf_denormalizeUsingReference(frame.width)
}
private var wmf_proportionalVerticalOffset: CGFloat{
return CGFloat(0.35).wmf_denormalizeUsingReference(frame.height)
}
var wmf_rightTransform: CATransform3D{
return CATransform3DMakeTranslation(wmf_proportionalHorizontalOffset, 0, 0)
}
var wmf_leftTransform: CATransform3D{
return CATransform3DMakeTranslation(-wmf_proportionalHorizontalOffset, 0, 0)
}
var wmf_lowerTransform: CATransform3D{
return CATransform3DMakeTranslation(0.0, wmf_proportionalVerticalOffset, 0)
}
let wmf_scaleZeroTransform = CATransform3DMakeScale(0, 0, 1)
var wmf_scaleZeroAndLeftTransform: CATransform3D{
return CATransform3DConcat(wmf_scaleZeroTransform, wmf_leftTransform)
}
var wmf_scaleZeroAndRightTransform: CATransform3D{
return CATransform3DConcat(wmf_scaleZeroTransform, wmf_rightTransform)
}
var wmf_scaleZeroAndLowerLeftTransform: CATransform3D{
return CATransform3DConcat(wmf_scaleZeroAndLeftTransform, wmf_lowerTransform)
}
var wmf_scaleZeroAndLowerRightTransform: CATransform3D {
return CATransform3DConcat(wmf_scaleZeroAndRightTransform, wmf_lowerTransform)
}
open func beginAnimations() {
}
open func addAnimationElementsScaledToCurrentFrameSize(){
}
public var hasCircleBackground: Bool = false {
didSet {
if hasCircleBackground {
backgroundColor = UIColor(0xdee6f6)
layer.masksToBounds = true
} else {
// backgroundColor = UIColor(0xdddddd)
backgroundColor = .clear
layer.masksToBounds = false
}
setNeedsLayout()
}
}
var sizeAtLastAnimationElementAddition = CGSize.zero
open override func layoutSubviews() {
super.layoutSubviews()
guard bounds.size != sizeAtLastAnimationElementAddition else {
return
}
sizeAtLastAnimationElementAddition = bounds.size
addAnimationElementsScaledToCurrentFrameSize()
if hasCircleBackground {
layer.cornerRadius = bounds.size.width / 2.0
} else {
layer.cornerRadius = 0
}
}
open func removeExistingSubviewsAndSublayers() {
for subview in subviews {
subview.removeFromSuperview()
}
if let sublayers = layer.sublayers {
for sublayer in sublayers {
sublayer.removeFromSuperlayer()
}
}
}
}
|
mit
|
5b2aa1bca7ae57a4f26a582041020b81
| 31.965909 | 88 | 0.661151 | 5.001724 | false | false | false | false |
RoverPlatform/rover-ios
|
Sources/UI/Services/VersionTracker/VersionTrackerService.swift
|
1
|
3316
|
//
// VersionTrackerService.swift
// RoverUI
//
// Created by Sean Rucker on 2018-06-21.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import Foundation
import os.log
#if !COCOAPODS
import RoverFoundation
import RoverData
#endif
class VersionTrackerService: VersionTracker {
let bundle: Bundle
let eventQueue: EventQueue
let userDefaults: UserDefaults
init(bundle: Bundle, eventQueue: EventQueue, userDefaults: UserDefaults) {
self.bundle = bundle
self.eventQueue = eventQueue
self.userDefaults = userDefaults
}
func checkAppVersion() {
guard let info = bundle.infoDictionary else {
os_log("Failed to check app version – missing bundle info", log: .general, type: .error)
return
}
let currentVersion = info["CFBundleShortVersionString"] as? String
let currentBuild = info["CFBundleVersion"] as? String
let versionString: (String?, String?) -> String = { version, build in
if let version = version {
if let build = build {
return "\(version) (\(build))"
}
return "\(version)"
}
return "n/a"
}
let currentVersionString = versionString(currentVersion, currentBuild)
os_log("Current version: %@", log: .general, type: .debug, currentVersionString)
let previousVersion = userDefaults.string(forKey: "io.rover.appVersion")
let previousBuild = userDefaults.string(forKey: "io.rover.appBuild")
let previousVersionString = versionString(previousVersion, previousBuild)
os_log("Previous version: %@", log: .general, type: .debug, previousVersionString)
if previousVersion == nil || previousBuild == nil {
os_log("Previous version not found – first time running app with Rover", log: .general, type: .debug)
trackAppInstalled()
} else if currentVersion != previousVersion || currentBuild != previousBuild {
os_log("Current and previous versions do not match – app has been updated", log: .general, type: .debug)
trackAppUpdated(fromVersion: previousVersion, build: previousBuild)
} else {
os_log("Current and previous versions match – nothing to track", log: .general, type: .debug)
}
userDefaults.set(currentVersion, forKey: "io.rover.appVersion")
userDefaults.set(currentBuild, forKey: "io.rover.appBuild")
}
func trackAppInstalled() {
let event = EventInfo(name: "App Installed", namespace: "rover")
eventQueue.addEvent(event)
}
func trackAppUpdated(fromVersion previousVersion: String?, build previousBuild: String?) {
let attributes = Attributes()
if let previousVersion = previousVersion {
attributes.rawValue["previousVersion"] = previousVersion
}
if let previousBuild = previousBuild {
attributes.rawValue["previousBuild"] = previousBuild
}
let event = EventInfo(name: "App Updated", namespace: "rover", attributes: attributes)
eventQueue.addEvent(event)
}
}
|
apache-2.0
|
22e4c727cb42e0838b7aeb3ed0b65ded
| 36.11236 | 116 | 0.620648 | 4.922504 | false | false | false | false |
vapor/vapor
|
Sources/Vapor/Concurrency/Request+Concurrency.swift
|
1
|
6708
|
#if compiler(>=5.7) && canImport(_Concurrency)
import NIOCore
import NIOConcurrencyHelpers
// MARK: - Request.Body.AsyncSequenceDelegate
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
extension Request.Body {
/// `Request.Body.AsyncSequenceDelegate` bridges between EventLoop
/// and AsyncSequence. Crucially, this type handles backpressure
/// by synchronizing bytes on the `EventLoop`
///
/// `AsyncSequenceDelegate` can be created and **must be retained**
/// in `Request.Body/makeAsyncIterator()` method.
fileprivate final class AsyncSequenceDelegate: @unchecked Sendable, NIOAsyncSequenceProducerDelegate {
private enum State {
case noSignalReceived
case waitingForSignalFromConsumer(EventLoopPromise<Void>)
}
private var _state: State = .noSignalReceived
private let eventLoop: any EventLoop
init(eventLoop: any EventLoop) {
self.eventLoop = eventLoop
}
private func produceMore0() {
self.eventLoop.preconditionInEventLoop()
switch self._state {
case .noSignalReceived:
preconditionFailure()
case .waitingForSignalFromConsumer(let promise):
self._state = .noSignalReceived
promise.succeed(())
}
}
private func didTerminate0() {
self.eventLoop.preconditionInEventLoop()
switch self._state {
case .noSignalReceived:
// we will inform the producer, since the next write will fail.
break
case .waitingForSignalFromConsumer(let promise):
self._state = .noSignalReceived
promise.fail(CancellationError())
}
}
func registerBackpressurePromise(_ promise: EventLoopPromise<Void>) {
self.eventLoop.preconditionInEventLoop()
switch self._state {
case .noSignalReceived:
self._state = .waitingForSignalFromConsumer(promise)
case .waitingForSignalFromConsumer:
preconditionFailure()
}
}
func didTerminate() {
self.eventLoop.execute { self.didTerminate0() }
}
func produceMore() {
self.eventLoop.execute { self.produceMore0() }
}
}
}
// MARK: - Request.Body.AsyncSequence
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
extension Request.Body: AsyncSequence {
public typealias Element = ByteBuffer
/// This wrapper generalizes our implementation.
/// `RequestBody.AsyncIterator` is the override point for
/// using another implementation
public struct AsyncIterator: AsyncIteratorProtocol {
public typealias Element = ByteBuffer
fileprivate typealias Underlying = NIOThrowingAsyncSequenceProducer<ByteBuffer, any Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Request.Body.AsyncSequenceDelegate>.AsyncIterator
private var underlying: Underlying
fileprivate init(underlying: Underlying) {
self.underlying = underlying
}
public mutating func next() async throws -> ByteBuffer? {
return try await self.underlying.next()
}
}
/// Checks that the request has a body suitable for an AsyncSequence
///
/// AsyncSequence streaming should use a body of type .stream().
/// Using `.collected(_)` will load the entire request into memory
/// which should be avoided for large file uploads.
///
/// Example: app.on(.POST, "/upload", body: .stream) { ... }
private func checkBodyStorage() {
switch request.bodyStorage {
case .stream(_):
break
case .collected(_):
break
default:
preconditionFailure("""
AsyncSequence streaming should use a body of type .stream()
Example: app.on(.POST, "/upload", body: .stream) { ... }
""")
}
}
/// Generates an `AsyncIterator` to stream the body’s content as
/// `ByteBuffer` sequences. This implementation supports backpressure using
/// `NIOAsyncSequenceProducerBackPressureStrategies`
/// - Returns: `AsyncIterator` containing the `Requeset.Body` as a
/// `ByteBuffer` sequence
public func makeAsyncIterator() -> AsyncIterator {
let delegate = AsyncSequenceDelegate(eventLoop: request.eventLoop)
let producer = NIOThrowingAsyncSequenceProducer.makeSequence(
elementType: ByteBuffer.self,
failureType: Error.self,
backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies
.HighLowWatermark(lowWatermark: 5, highWatermark: 20),
delegate: delegate
)
let source = producer.source
self.drain { streamResult in
switch streamResult {
case .buffer(let buffer):
// Send the buffer to the async sequence
let result = source.yield(buffer)
// Inspect the source view and handle outcomes
switch result {
case .dropped:
// The consumer dropped the sequence.
// Inform the producer that we don't want more data
// by returning an error in the future.
return request.eventLoop.makeFailedFuture(CancellationError())
case .stopProducing:
// The consumer is too slow.
// We need to create a promise that we succeed later.
let promise = request.eventLoop.makePromise(of: Void.self)
// We pass the promise to the delegate so that we can succeed it,
// once we get a call to `delegate.produceMore()`.
delegate.registerBackpressurePromise(promise)
// return the future that we will fulfill eventually.
return promise.futureResult
case .produceMore:
// We can produce more immidately. Return a succeeded future.
return request.eventLoop.makeSucceededVoidFuture()
}
case .error(let error):
source.finish(error)
return request.eventLoop.makeSucceededVoidFuture()
case .end:
source.finish()
return request.eventLoop.makeSucceededVoidFuture()
}
}
return AsyncIterator(underlying: producer.sequence.makeAsyncIterator())
}
}
#endif
|
mit
|
2337d2dd6f6a5ec1fc0fb22f7c882974
| 38.216374 | 213 | 0.605279 | 5.510271 | false | false | false | false |
coach-plus/ios
|
Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift
|
6
|
7718
|
//
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an object that is both an observable sequence as well as an observer.
///
/// Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
public class ReplaySubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
self._lock.lock()
let value = self._observers.count > 0
self._lock.unlock()
return value
}
fileprivate let _lock = RecursiveLock()
// state
fileprivate var _isDisposed = false
fileprivate var _isStopped = false
fileprivate var _stoppedEvent = nil as Event<Element>? {
didSet {
self._isStopped = self._stoppedEvent != nil
}
}
fileprivate var _observers = Observers()
#if DEBUG
fileprivate let _synchronizationTracker = SynchronizationTracker()
#endif
func unsubscribe(_ key: DisposeKey) {
rxAbstractMethod()
}
final var isStopped: Bool {
return self._isStopped
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<Element>) {
rxAbstractMethod()
}
/// Returns observer interface for subject.
public func asObserver() -> SubjectObserverType {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
}
/// Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
///
/// - parameter bufferSize: Maximal number of elements to replay to observer after subscription.
/// - returns: New instance of replay subject.
public static func create(bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
}
else {
return ReplayMany(bufferSize: bufferSize)
}
}
/// Creates a new instance of `ReplaySubject` that buffers all the elements of a sequence.
/// To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable'
/// number of elements.
public static func createUnbounded() -> ReplaySubject<Element> {
return ReplayAll()
}
#if TRACE_RESOURCES
override init() {
_ = Resources.incrementTotal()
}
deinit {
_ = Resources.decrementTotal()
}
#endif
}
private class ReplayBufferBase<Element>
: ReplaySubject<Element>
, SynchronizedUnsubscribeType {
func trim() {
rxAbstractMethod()
}
func addValueToBuffer(_ value: Element) {
rxAbstractMethod()
}
func replayBuffer<Observer: ObserverType>(_ observer: Observer) where Observer.Element == Element {
rxAbstractMethod()
}
override func on(_ event: Event<Element>) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
dispatch(self._synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<Element>) -> Observers {
self._lock.lock(); defer { self._lock.unlock() }
if self._isDisposed {
return Observers()
}
if self._isStopped {
return Observers()
}
switch event {
case .next(let element):
self.addValueToBuffer(element)
self.trim()
return self._observers
case .error, .completed:
self._stoppedEvent = event
self.trim()
let observers = self._observers
self._observers.removeAll()
return observers
}
}
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock()
let subscription = self._synchronized_subscribe(observer)
self._lock.unlock()
return subscription
}
func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
if self._isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
let anyObserver = observer.asObserver()
self.replayBuffer(anyObserver)
if let stoppedEvent = self._stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
else {
let key = self._observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock()
self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if self._isDisposed {
return
}
_ = self._observers.removeKey(disposeKey)
}
override func dispose() {
super.dispose()
self.synchronizedDispose()
}
func synchronizedDispose() {
self._lock.lock()
self._synchronized_dispose()
self._lock.unlock()
}
func _synchronized_dispose() {
self._isDisposed = true
self._observers.removeAll()
}
}
private final class ReplayOne<Element> : ReplayBufferBase<Element> {
private var _value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(_ value: Element) {
self._value = value
}
override func replayBuffer<Observer: ObserverType>(_ observer: Observer) where Observer.Element == Element {
if let value = self._value {
observer.on(.next(value))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
self._value = nil
}
}
private class ReplayManyBase<Element>: ReplayBufferBase<Element> {
fileprivate var _queue: Queue<Element>
init(queueSize: Int) {
self._queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(_ value: Element) {
self._queue.enqueue(value)
}
override func replayBuffer<Observer: ObserverType>(_ observer: Observer) where Observer.Element == Element {
for item in self._queue {
observer.on(.next(item))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
self._queue = Queue(capacity: 0)
}
}
private final class ReplayMany<Element> : ReplayManyBase<Element> {
private let _bufferSize: Int
init(bufferSize: Int) {
self._bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while self._queue.count > self._bufferSize {
_ = self._queue.dequeue()
}
}
}
private final class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
}
|
mit
|
3463f309d46968408724f6b6eb9e9852
| 26.462633 | 128 | 0.605805 | 5.02082 | false | false | false | false |
GianniCarlo/Audiobook-Player
|
BookPlayer/Settings/Storage/StorageViewController.swift
|
1
|
4664
|
//
// StorageViewController.swift
// BookPlayer
//
// Created by Gianni Carlo on 19/8/21.
// Copyright © 2021 Tortuga Power. All rights reserved.
//
import BookPlayerKit
import Combine
import Themeable
import UIKit
final class StorageViewController: UIViewController {
@IBOutlet weak var filesTitleLabel: LocalizableLabel!
@IBOutlet weak var storageSpaceLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var loadingViewIndicator: UIActivityIndicatorView!
@IBOutlet var titleLabels: [UILabel]!
@IBOutlet var containerViews: [UIView]!
@IBOutlet var separatorViews: [UIView]!
private var viewModel = StorageViewModel()
private var disposeBag = Set<AnyCancellable>()
private var items = [StorageItem]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "settings_storage_title".localized
self.tableView.tableFooterView = UIView()
self.tableView.isScrollEnabled = true
self.storageSpaceLabel.text = viewModel.getLibrarySize()
self.bindItems()
setUpTheming()
}
private func bindItems() {
self.viewModel.observeFiles()
.receive(on: DispatchQueue.main)
.sink { [weak self] storageItems in
guard !storageItems.isEmpty else { return }
self?.items = storageItems
self?.filesTitleLabel.text = "\("files_caps_title".localized) - \(storageItems.count)"
self?.tableView.reloadData()
self?.loadingViewIndicator.stopAnimating()
}.store(in: &disposeBag)
}
}
extension StorageViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// swiftlint:disable force_cast
let cell = tableView.dequeueReusableCell(withIdentifier: "StorageTableViewCell", for: indexPath) as! StorageTableViewCell
let item = self.items[indexPath.row]
cell.titleLabel.text = item.title
cell.sizeLabel.text = item.formattedSize()
cell.filenameLabel.text = item.path
cell.warningButton.isHidden = !item.showWarning
cell.onWarningTap = { [weak self] in
let alert = UIAlertController(title: nil,
message: "storage_fix_file_description".localized,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "cancel_button".localized, style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "storage_fix_file_button".localized, style: .default, handler: { [weak self] _ in
do {
try self?.viewModel.handleFix(for: item)
} catch {
self?.showAlert("error_title".localized, message: error.localizedDescription)
}
}))
self?.present(alert, animated: true, completion: nil)
}
cell.onDeleteTap = { [weak self] in
let alert = UIAlertController(title: nil,
message: String(format: "delete_single_item_title".localized, item.title),
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "cancel_button".localized, style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "delete_button".localized, style: .destructive, handler: { _ in
do {
try self?.viewModel.handleDelete(for: item)
} catch {
self?.showAlert("error_title".localized, message: error.localizedDescription)
}
}))
self?.present(alert, animated: true, completion: nil)
}
return cell
}
}
extension StorageViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
extension StorageViewController: Themeable {
func applyTheme(_ theme: Theme) {
self.view.backgroundColor = theme.systemGroupedBackgroundColor
self.tableView.backgroundColor = theme.systemBackgroundColor
self.tableView.separatorColor = theme.separatorColor
self.storageSpaceLabel.textColor = theme.secondaryColor
self.separatorViews.forEach { separatorView in
separatorView.backgroundColor = theme.separatorColor
}
self.containerViews.forEach { view in
view.backgroundColor = theme.systemBackgroundColor
}
self.titleLabels.forEach { label in
label.textColor = theme.primaryColor
}
self.tableView.reloadData()
self.overrideUserInterfaceStyle = theme.useDarkVariant
? UIUserInterfaceStyle.dark
: UIUserInterfaceStyle.light
}
}
|
gpl-3.0
|
0db507ea3bdc6e2ff4e55601ea47810d
| 31.381944 | 125 | 0.693974 | 4.724417 | false | false | false | false |
readium/r2-streamer-swift
|
r2-streamer-swift/Parser/EPUB/NCXParser.swift
|
1
|
2746
|
//
// NCXParser.swift
// r2-streamer-swift
//
// Created by Alexandre Camilleri on 3/17/17.
//
// Copyright 2018 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import R2Shared
import Fuzi
import Foundation
/// From IDPF a11y-guidelines content/nav/toc.html :
/// "The NCX file is allowed for forwards compatibility purposes only. An EPUB 2
/// reading systems may open an EPUB 3 publication, but it will not be able to
/// use the new navigation document format.
/// You can ignore the NCX file if your book won't render properly as EPUB 2
/// content, or if you aren't targeting cross-compatibility."
final class NCXParser {
enum NavType: String {
case tableOfContents = "navMap"
case pageList = "pageList"
}
private let data: Data
private let path: String
/// Builds the NCX parser from the NCX data and its path. The path is used to normalize the links' hrefs.
init(data: Data, at path: String) {
self.data = data
self.path = path
}
private lazy var document: Fuzi.XMLDocument? = {
let document = try? XMLDocument(data: data)
document?.definePrefix("ncx", forNamespace: "http://www.daisy.org/z3986/2005/ncx/")
return document
}()
/// Returns the [Link] representation of the navigation list of given type (eg. pageList).
func links(for type: NavType) -> [Link] {
let nodeTagName: String = {
if case .pageList = type {
return "pageTarget"
} else {
return "navPoint"
}
}()
guard let document = document,
let nav = document.firstChild(xpath: "/ncx:ncx/ncx:\(type.rawValue)") else
{
return []
}
return links(in: nav, nodeTagName: nodeTagName)
}
/// Parses recursively a list of nodes as a list of `Link`.
private func links(in element: Fuzi.XMLElement, nodeTagName: String) -> [Link] {
return element.xpath("ncx:\(nodeTagName)")
.compactMap { self.link(for: $0, nodeTagName: nodeTagName) }
}
/// Parses a node element as a `Link`.
private func link(for element: Fuzi.XMLElement, nodeTagName: String) -> Link? {
return NavigationDocumentParser.makeLink(
title: element.firstChild(xpath: "ncx:navLabel/ncx:text")?.stringValue,
href: element.firstChild(xpath: "ncx:content")?.attr("src"),
children: links(in: element, nodeTagName: nodeTagName),
basePath: path
)
}
}
|
bsd-3-clause
|
3f0d36a7712bc871c70b19e14d1bb5b2
| 33.759494 | 109 | 0.62673 | 4.179604 | false | false | false | false |
beeth0ven/BNKit
|
BNKit/Source/UIKit+/Cell+Init.swift
|
1
|
2308
|
//
// Cell+Init.swift
// show
//
// Created by luojie on 16/5/13.
// Copyright © 2016年 @天意. All rights reserved.
//
import UIKit
// UITableViewCell
public protocol IsTableViewCell {}
extension UITableViewCell: IsTableViewCell {}
extension IsTableViewCell where Self: UITableViewCell {
public static func dequeue(from tableView: UITableView) -> Self {
let identifier = String(describing: self)
guard let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? Self else {
fatalError("Can't get \(identifier) from tableView!")
}
return cell
}
}
extension IsTableViewCell where Self: UITableViewCell, Self: HasModel {
public static func dequeue(from tableView: UITableView, withModel model: Model!) -> Self {
var cell = self.dequeue(from: tableView)
cell.model = model
return cell
}
}
// UICollectionViewCell
public protocol IsCollectionViewCell {}
extension UICollectionViewCell: IsCollectionViewCell {}
extension IsCollectionViewCell where Self: UICollectionViewCell {
public static func dequeue(from collectionView: UICollectionView, forIndexPath indexPath: IndexPath) -> Self {
let identifier = String(describing: self)
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? Self else {
fatalError("Can't get \(identifier) from collectionView!")
}
return cell
}
public static func dequeue(from collectionView: UICollectionView, forIndex index: Int) -> Self {
return dequeue(from: collectionView, forIndexPath: IndexPath(item: index, section: 0))
}
}
extension IsCollectionViewCell where Self: UICollectionViewCell, Self: HasModel {
public static func dequeue(from collectionView: UICollectionView, forIndexPath indexPath: IndexPath, withModel model: Model!) -> Self {
var cell = self.dequeue(from: collectionView, forIndexPath: indexPath)
cell.model = model
return cell
}
public static func dequeue(from collectionView: UICollectionView, forIndex index: Int, withModel model: Model!) -> Self {
return dequeue(from: collectionView, forIndexPath: IndexPath(item: index, section: 0), withModel: model)
}
}
|
mit
|
0a850722b6a37dcaf27c66d83958123e
| 34.953125 | 139 | 0.707953 | 4.980519 | false | false | false | false |
BiteCoda/icebreaker-app
|
IceBreaker-iOS/IceBreaker/Models/Beacon.swift
|
1
|
726
|
//
// Beacon.swift
// IceBreaker
//
// Created by Jacob Chen on 2/21/15.
// Copyright (c) 2015 floridapoly.IceMakers. All rights reserved.
//
import Foundation
// For now assume that you have an associated Beacon ID
private let _SingletonSharedBeacon = Beacon(majID: 46555, minID: 50000)
class Beacon {
var majorID: NSNumber?
var minorID: NSNumber?
let beaconsTried: Queue = Queue(queueSize: 3)
var beaconsConnected:[Beacon] = []
class var sharedBeacon : Beacon {
return _SingletonSharedBeacon
}
init() {
}
init (majID: NSNumber, minID: NSNumber) {
self.majorID = majID
self.minorID = minID
}
}
|
gpl-3.0
|
e6e3cd088c3f8f7a8207329a31e4d762
| 18.648649 | 71 | 0.604683 | 3.742268 | false | false | false | false |
austinzheng/swift-compiler-crashes
|
crashes-duplicates/00176-vtable.swift
|
12
|
12851
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b<d-> d { class d:b class b
class l {
func f((k, l() -> f
}
class d
}
class i: d, g {
l func d() -> f {
m ""
}
}
}
func m<j n j: g, j: d
let l = h
l()
f
protocol l : f { func f
protocol g
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
protocol f {
k g d {
k d
k k
}
j j<l : d> : d {
k , d>
}
class f: f {
}
class B : l {
}
k l = B
class f<i : f
)
func n<w>() -> (w, w -> w) -> w {
o m o.q = {
}
{
w) {
k }
}
protocol n {
class func q()
}
class o: n{ class func q {}
func p(e: Int = x) {
}
let c = p
c()
func r<o: y, s q n<s> ==(r(t))
protocol p : p {
}
protocol p {
class func c()
}
class e: p {
class func c() { }
}
(e() u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) {
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
i)
import Foundation
class q<k>: NSObject {
var j: k
e ^(l: m, h) -> h {
f !(l)
}
protocol l {
d g n()
}
class h: l {
class g n() { }
}
(h() o l).p.n()
class l<n : h,
q
var m: Int -> Int = {
n $0
o: Int = { d, l f
n l(d)
}(k, m)
protocol j {
typealias d
typealias n = d
typealias l = d}
class g<q : l, m : l p q.g == m> : j {
}
class g<q, m> {
}
protocol l {
typealias g
d)
func e(h: b) -> <f>(() -> f) -> b {
return { c):h())" }
}
func b<d {
enum b {
func c
var _ = c
}
}
}
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
p d
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class r {
typealias n = n
struct c<e> {
let d: i h
}
func f(h: b) -> <e>(()-> e
func d(b: String-> <c>() -> c)
class A<T : A> {
}
class a {
typealias b = b
}
b
protocol d : b { func b
func d(e: = { (g: h, f: h -> h) -> h in
return f(g)
}
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
func a<d>() -> [c{ enum b {
case c
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
d ""
e}
class d {
func b((Any, d)typealias b = b
func ^(a: BooleanType, Bool) -> Bool {
return !(a)
}
func r<t>() {
f f {
i i
}
}
struct i<o : u> {
o f: o
}
func r<o>() -> [i<o>] {
p []
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
typealias h = n
protocol g {
func i() -> l func o() -> m {
q""
}
}
func j<t k t: g, t: n>(s: t) {
s.i()
}
protocol r {
}
protocol f : r {
}
protocol i : r {
}
j
protocol a {
}
protocol h : a {
}
protocol k : a {
}
protocol g {
j n = a
}
struct n : g {
j n = h
}
func i<h : h, f : g m f.n == h> (g: f) {
}
func i<n : g m n.n = o) {
}
let k = a
k()
h
protocol k : h { func h
k
protocol a : a {
}
func b(c) -> <d>(() -> d) {
}
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
self.b = b
}
}
protocol A {
typealias B
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
}
}
protocol l {
class func i()
}
class o: l{ class func i {}
class h: h {
}
class m : C {
}
typealias C = m
func s<S: y, t i o<t> == S.k.b>(r : S) -> t? {
j (u : t?) q r {
l let g = u {
p g
}
}
p v
}
let r : [n?] = [w o = h
typealias h = x<g<h
struct l<e : SequenceType> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
class A<T : A> {
}
func c<d {
enum c {
func e
var _ = e
}
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicl A {
{
typealias b = b
d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}}
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
class f<d : d, j : d k d.l == j> {
}
protocol d {
i l
i i
}
struct l<l : d> : d {
i j i() {
l.i()
}
}
protocol f {
}
protocol d : f {
func i(f: g) -> <j>(() -> j) -> g { func g
k, l {
typealias l = m<k<m>, f>
}
class j {
func y((Any, j))(v: (Any, AnyObject)) {
y(v)
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
({})
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
u n
}
y q<x> {
s w(x, () -> ())
}
o n {
func j() p
}
class r {
func s() -> p {
t ""
}
}
class w: r, n {
k v: ))] = []
}
class n<x : n>
func p<p>() -> (p, p -> p) -> p {
l c l.l = {
}
{
p) {
(e: o, h:o) -> e
})
}
j(k(m, k(2, 3)))
func l(p: j) -> <n>(() -> n
}
e
protocol h : e { func e
func r(d: t, k: t) -> (((t, t) -> t) -i g {
p m
func e(m)
}
struct e<j> : g {
func e(
h s: n -> n = {
return $u
}
l o: n = { (d: n, o: n -> n) -> n q
return o(d)
}
class A: A {
}
class B : C {
}
typealias C = B
n)
func f<o>() -> (o, o -> o) -> o {
o m o.j = {
}
{
o) {
r }
}
p q) {
}
o m = j
m()
class m {
func r((Any, m))(j: (Any, AnyObject)) {
r(j)
}
}
func m<o {
r m {
func n
n _ = n
}
}
class k<l : k
w
class x<u>: d {
l i: u
init(i: u) {
o.i = j {
r { w s "\(f): \(w())" }
}
protocol h {
q k {
t w
}
w
protocol k : w { func v <h: h m h.p == k>(l: h.p) {
}
}
protocol h {
n func w(w:
}
class h<u : h> {
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
u) {
o }
}
s m {
class func s()
}
class p: m{ class func s {}
s p {
func m() -> String
}
class n {
func p() -> String {
q ""
}
}
class e: n, p {
v func> String {
q ""
}
{
r m = m
}
func s<o : m, o : p o o.m == o> (m: o) {
}
func s<v : p o v.m == m> (u: String) -> <t>(() -> t) -
struct c<d: SequenceType, b where Optional<b> == d.Generator.Element>
func f<m>() -> (m, m -> m) -> m {
e c e.i = {
}
{
m) {
n }
}
protocol f {
class func i()
}
class e: f{ class func i {}
func n<j>() -> (j, j -> j) -> j {
var m: ((j> j)!
f m
}
protocol k {
typealias m
}
struct e<j : k> {n: j
let i: j.m
}
l
({})
protocol f : f {
}
func h<d {
enum h {
func e
var _ = e
}
}
protocol e {
e func e()
}
struct h {
var d: e.h
func e() {
d.e()
}
}
protocol f {
i []
}
func f<g>() -> (g, g -> g) -> g
struct c<d : SequenceType> {
var b: [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type
func e() {
d.e()
}
}
b
protocol c : b { func b
otocol A {
E == F>(f: B<T>)
}
struct }
}
func a(b: Int = 0) {
}
let c = a
c()
protocol p {
class func g()
}
class h: p {
class func g() { }
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
o t = p
}
struct h : n {
t : n q m.t == m> (h: m) {
}
func q<t : n q t.t == g> (h: t) {
}
q(h())
func r(g: m) -> <s>(() -> s) -> n
}func h(c: j) -> <i>(() -> i) -> b {
f j = e
func j<i k i.l == j>(d: B<i>)
f g
}
struct d<i : b> : b {
typealias b = i
typealias g = a<d<i>i) {
}
let d = a
d()
a=d g a=d
protocol a : a {
}
class a {
typealias b = b
func b<e>(e : e) -> c { e
)
func t<v>() -> (v, v -> v) -> v {
var d: ((v, v -> v) -> v)!
q d
}
protocol t {
}
protocol d : t {
}
protocol g : t {
}
s
q l
})
}
d(t(u, t(w, y)))
protocol e {
r j
}
struct m<v : e> {
k x: v
k x: v.j
}
protocol n {
g == o>(n: m<v>) {
}
}
struct e<v> {
k t: [(v, () -> ())] = [](m)
}
struct d<x> : e {
func d(d: d.p) {
}
}
class e<v : e> {
}
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
)
var d = b
=b as c=b
func d() -> String {
return 1
k f {
typealias c
}
class g<i{
}
d(j i)
class h {
typealias i = i
}
protocol A {
func c()l k {
func l() -> g {
m ""
}
}
class C: k, A {
j func l()q c() -> g {
m ""
}
}
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
import Foundation
class Foo<T>: NSObject {
var foo: T
init(foo: T) {
B>(t: T) {
t.y) -> Any) -> Any l
k s(j, t)
}
}
func b(s: (((Any, Any) -> Any) -> Any)
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g = g
func a<T>() {
enum b {
case c
}
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
class func f()
}
class d: c{ class func f {}
struct d<c : f,f where g.i == c.i>
class k<g>: d {
var f: g
init(f: g) {
self.f = f
l. d {
typealias i = l
typealias j = j<i<l>, i>
}
class j {
typealias d = d
func f() {
({})
}
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h: j, m {
q o m() -> String {
n ""
}
o u() -> S, q> {
}
protocol u {
typealias u
}
class p {
typealias u = u
func k<q {
enum k {
func j
var _ = j
}
}
class x {
s m
func j(m)
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
let u: v.l
}
protocol y {
o= p>(r: m<v>)
}
struct D : y {
s p = Int
func y<v k r {
s m
}
class y<D> {
w <r:
func j<v x: v) {
x.k()
}
func x(j: Int = a) {
}
let k = x
func g<h>() -> (h, h -> h) -> h {
f f: ((h, h -> h) -> h)!
j f
}
protocol f {
class func j()
}
struct i {
f d: f.i
func j() {
d.j()
}
}
class g {
typealias f = f
}
func g(f: Int = k) {
}
let i = g
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
o
class w<r>: c {
init(g: r) {
n.g = g
s.init()
(t: o
struct t : o {
p v = t
}
q t<where n.v == t<v : o u m : v {
}
struct h<t, j: v where t.h == j
struct A<T> {
let a: [(T, () -> ())] = []
}
func f<r>() -> (r, r -> r) -> r {
f r f.j = {
}
{
r) {
s }
}
protocol f {
class func j()
}
class f: f{ class func j {}
protocol j {
class func m()
}
class r: j {
class func m() { }
}
(r() n j).p.m()
j=k n j=k
protocol r {
class func q()
}
s m {
m f: r.q
func q() {
f.q()
}
(l, () -> ())
}
func f<l : o>(r: l)
import Foundation
class m<j>: NSObject {
var h: j
g -> k = l $n
}
b f: _ = j() {
}
}
func k<g {
enum k {
func l
var _ = l
}
class d {
func l<j where j: h, j: d>(l: j) {
l.k()
}
func i(k: b) -> <j>(() -> j) -> b {
f { m m "\(k): \(m())" }
}
protocol h
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
}
}
struct c<d : SequenceType> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
protocol a {
}
protocol b : a {
}
protocol c : a {
}
protocol d {
typealias f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
i(e())
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
class func i()
}
class k: c{ class func i {
a
}
struct e : f {
i f = g
}
func i<g : g, e : f where e.f == g> (c: e) {
}
func i<h : f where h.f == c> (c: h) {
}
i(e())
class a<f : g, g alias g = g
|
mit
|
ba6c141fbca65db2bdb9b730568b3409
| 11.980808 | 87 | 0.407206 | 2.282593 | false | false | false | false |
ccwuzhou/WWZSwift
|
Source/Extensions/String+WWZ.swift
|
1
|
5972
|
//
// String+WWZ.swift
// WWZSwift
//
// Created by wwz on 17/3/7.
// Copyright © 2017年 tijio. All rights reserved.
//
import Foundation
public extension String {
/**
* MD5加密
*/
/*
var md5 : String {
let str = self.cString(using: String.Encoding.utf8)
let strLen = (CC_LONG)(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5(str!, strLen, result)
var hash = String()
for i in 0 ..< digestLen {
hash = hash.appendingFormat("%02x", result[i])
}
result.deinitialize()
return hash
}
*/
/**
* 得到十六进制字符
*/
public var wwz_sixteenthTypeString : String {
if let intValue = Int(self) {
return String().appendingFormat("%x", intValue)
}else{
return "0"
}
}
public var wwz_tenTypeValue : Int {
let str = self.uppercased()
var number = 0
for i in str.utf8 {
number = number * 16 + Int(i) - 48
if i >= 65 {
number -= 7
}
}
return number
}
/**
* NSDocumentDirectory 中文件路径
*/
public static func wwz_filePath(fileName: String) -> String {
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
return documentPath.appending("/\(fileName)")
}
/**
* 指定长度字符串(从后面截取)
*
* @param length 截取长度
*
* @return 指定长度字符串,不足前面补0
*/
public func wwz_fixedString(length: Int) -> String {
let strLength = self.characters.count
if strLength >= length {
return self.substring(from: self.index(self.startIndex, offsetBy: strLength - length))
}else{
var mString = self
for _ in 0..<length-strLength {
mString = "0\(mString)"
}
return mString
}
}
public func stringArray() -> [String] {
var dataArray = [String]()
for item in self.characters {
dataArray.append("\(item)")
}
return dataArray
}
// MARK: -下标扩展
/// 获取单
public subscript(n: Int) -> Character?{
guard n < self.characters.count, n >= 0 else {
return nil
}
let index = self.characters.index(self.characters.startIndex, offsetBy:n)
return self.characters[index]
}
// 从0开始的close range
public subscript (range: CountableClosedRange<Int>) -> String{
get {
if range.lowerBound >= self.characters.count { return "" }
let startIndex = range.lowerBound <= 0 ? self.startIndex : self.index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = range.upperBound < self.characters.count ? self.index(self.startIndex, offsetBy: range.upperBound) : self.endIndex
return self.substring(with: startIndex..<endIndex)
}
}
}
extension String {
public func wwz_jsonFormat() -> String {
let spacing = "\t"
let enterKey = "\n"
var number = 0
let addSpaceBlock : (Int)-> String = { num in
var mString = String()
for _ in 0..<num {
mString.append(spacing)
}
return mString
}
let firstCharacter = self[0...1]
var mString = "\n" + firstCharacter
if firstCharacter == "[" || firstCharacter == "{" {
mString.append(enterKey)
number += 1
mString.append(addSpaceBlock(number))
}
var isInQuotation = false
for i in 0...self.characters.count {
let subC = self[i...i+1]
if subC == "\"" && self[i-1...i] != "\\" {
isInQuotation = !isInQuotation
}
if isInQuotation {
mString.append(subC)
continue
}
if subC == "[" || subC == "{" {
if self[i-1...i] == ":" {
mString.append(enterKey)
mString.append(addSpaceBlock(number))
}
mString.append(subC+enterKey)
number += 1
mString.append(addSpaceBlock(number))
}else if subC == "]" || subC == "}" {
mString.append(enterKey)
number -= 1
mString.append(addSpaceBlock(number))
mString.append(subC)
if i+1 < self.characters.count && self[i+1...i+2] != "," {
mString.append(enterKey)
}
}else if subC == "," {
mString.append(subC)
mString.append(enterKey)
mString.append(addSpaceBlock(number))
}else {
mString.append(subC)
}
}
return mString
}
}
|
mit
|
b196bde2e40111a4b88c754447d0312f
| 23.914894 | 141 | 0.438087 | 5.017138 | false | false | false | false |
looklikes/DouYuTV
|
DouYuTV/DouYuTV/RecommendViewController.swift
|
1
|
4183
|
//
// RecommendViewController.swift
// DouYuTV
//
// Created by Apple on 2017/9/6.
// Copyright © 2017年 Apple. All rights reserved.
//
import UIKit
private let itemMargin : CGFloat = 10
private let itemW : CGFloat = (screenW - 3 * itemMargin) / 2
private let normalItemH : CGFloat = itemW * 3 / 4
private let beautyItemH : CGFloat = itemW * 4 / 3
private let headerViewH : CGFloat = 50
private let normalCellID : String = "normalCellID"
private let beautyCellID : String = "beautyCellID"
private let headerViewID : String = "headerViewID"
class RecommendViewController: UIViewController {
// MARK:- 懒加载属性
private lazy var recommendViewModel : RecommendViewModel = RecommendViewModel()
private lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: itemW, height: normalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = itemMargin
layout.headerReferenceSize = CGSize(width: screenW, height: headerViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: itemMargin, bottom: 0, right: itemMargin)
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
//设置collectionView灵活宽高
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "NormalCollectionCell", bundle: nil), forCellWithReuseIdentifier: normalCellID)
collectionView.register(UINib(nibName: "BeautyCollectionCell", bundle: nil), forCellWithReuseIdentifier: beautyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewID)
collectionView.backgroundColor = UIColor(white: 1, alpha: 1)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
//MARK: - 设置UI
self.view.addSubview(collectionView)
//MARK: - 发送网络请求
recommendViewModel.requestData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 遵守UICollectionView的数据源协议
extension RecommendViewController : UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 8
}
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : UICollectionViewCell!
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: beautyCellID, for: indexPath)
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: normalCellID, for: indexPath)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerViewID, for: indexPath)
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: itemW, height: beautyItemH)
}
return CGSize(width: itemW, height: normalItemH)
}
}
|
mit
|
f9b73dd37c77f97535f078115abbf105
| 37.811321 | 185 | 0.693486 | 5.753846 | false | false | false | false |
duliodenis/pocket-critter-go
|
Pokecrit Go/Pokecrit Go/Controllers/MapViewController.swift
|
1
|
4329
|
//
// MapViewController.swift
// Pokecrit Go
//
// Created by Dulio Denis on 5/5/17.
// Copyright © 2017 ddApps. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
var numberOfUpdates = 0
var pokecrits: [Pokecrit] = []
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
mapView.delegate = self
pokecrits = getAllPokecrits()
// if we are authorized to show location - display it
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
mapView.showsUserLocation = true
locationManager.startUpdatingLocation()
// start a timer for the critter spawn
Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (timer) in
if let coordinate = self.locationManager.location?.coordinate {
let randomPokecrit = self.pokecrits[Int(arc4random_uniform(UInt32(self.pokecrits.count)))]
let annotation = PokecritAnnotation(coordinate: coordinate, pokecrit: randomPokecrit)
// Randomize the location of spawn
annotation.coordinate.latitude += (Double(arc4random_uniform(1000)) - 500) / 300000.0
annotation.coordinate.longitude += (Double(arc4random_uniform(1000)) - 500) / 300000.0
self.mapView.addAnnotation(annotation)
}
})
} else {
// otherwise request it
locationManager.requestWhenInUseAuthorization()
}
}
// MARK: - Update User Location
@IBAction func updateLocation(_ sender: Any) {
updateMap()
}
}
// MARK: - Location Manager Delegate Method
extension MapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// update 4 times and then halt until requested to update
if numberOfUpdates < 4 {
updateMap()
numberOfUpdates += 1
} else {
locationManager.stopUpdatingLocation()
}
}
}
// MARK: - Map View Delegate Methods
extension MapViewController: MKMapViewDelegate {
func updateMap() {
let region = MKCoordinateRegionMakeWithDistance(locationManager.location!.coordinate, 400, 400)
mapView.setRegion(region, animated: true)
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
mapView.deselectAnnotation(view.annotation, animated: true)
// ignore the user
if view.annotation! is MKUserLocation {
return
}
// establish a tighter capture region
let region = MKCoordinateRegionMakeWithDistance(view.annotation!.coordinate, 150, 150)
mapView.setRegion(region, animated: false)
if let coordinate = locationManager.location?.coordinate {
let ann = view.annotation as! PokecritAnnotation
if MKMapRectContainsPoint(mapView.visibleMapRect, MKMapPointForCoordinate(coordinate)) {
print("Capture \(ann.pokecrit.name!).")
let battle = BattleViewController()
battle.pokecrit = ann.pokecrit
present(battle, animated: true)
} else {
print("Too far to capture \(ann.pokecrit.name!).")
}
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
if annotation is MKUserLocation {
annotationView.image = UIImage(named: "pin")
} else {
let pokecrit = (annotation as! PokecritAnnotation).pokecrit
annotationView.image = UIImage(named: pokecrit.imageURL!)
}
var newFrame = annotationView.frame
newFrame.size.height = 40
newFrame.size.width = 40
annotationView.frame = newFrame
return annotationView
}
}
|
mit
|
15dcffcb6b1e5777915d2a5e3fcbd2bd
| 31.541353 | 110 | 0.613909 | 5.208183 | false | false | false | false |
alitan2014/swift
|
Heath/Heath/Controllers/SymptomViewController.swift
|
1
|
18060
|
//
// SymptomViewController.swift
// Heath
//
// Created by TCL on 15/8/14.
// Copyright (c) 2015年 Mac. All rights reserved.
//
import UIKit
import Alamofire
import SystemConfiguration
class SymptomViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var bgView:UIView!
var activity:UIActivityIndicatorView!
var position:String!
var personType:String!
var IPHONE_WIDTH:CGFloat=UIScreen.mainScreen().bounds.width
var IPHONE_HEIGHT:CGFloat=UIScreen.mainScreen().bounds.height
var symptomTableView:UITableView!
var bodyTableView:UITableView!
var symptomArray:NSMutableArray!
var bodyArray:NSMutableArray!
var typeNum:NSNumber!
var index:Int!
var personString:String!
var bodyString:String!
var dataArr:NSMutableArray!
var bodyArr:NSMutableArray!
var nameArr:NSMutableArray!
var idArr:NSMutableArray!
var sex:String!
internal class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.userInteractionEnabled=true
self.dataArr=NSMutableArray()
if Reachability.isConnectedToNetwork(){
createUI()
loadData()
initData()
println("网络连接正常,继续...")
}else{
println("网络异常...")
// initData()
createUI()
// loadData()
readWithFile()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.hidden=true
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.hidesBottomBarWhenPushed=true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//从网络中加载数据
func loadData()
{
self.view.addSubview(self.bgView)
self.activity.startAnimating()
UIApplication.sharedApplication().networkActivityIndicatorVisible=true
bodyArr=NSMutableArray()
nameArr=NSMutableArray()
idArr=NSMutableArray()
if self.personType=="男性"
{
sex="1"
}else if self.personType=="女性"
{
sex="2"
}
Alamofire.request(.POST, "http://app.zmyy.cn/Api_inc/daozhen/datasource.php", parameters: ["sex":sex]).responseJSON(options: NSJSONReadingOptions.MutableContainers) { (_, _, JSON, _) -> Void in
let refudeArray=JSON!.objectForKey("data")as!NSArray
for dic in refudeArray
{
var model = PositionModel()
model.setValuesForKeysWithDictionary(dic as![NSObject:AnyObject])
self.dataArr.addObject(model)
self.bodyArr.addObject(model.jbname)
var sytomArr=NSMutableArray()
var idArray=NSMutableArray()
for var i=0;i<model.jblistArr.count;i++
{
var jbModel:JBModel=model.jblistArr.objectAtIndex(i) as!JBModel
sytomArr.addObject(jbModel.jbname)
self.idArr.addObject(jbModel.id)
}
self.nameArr.addObject(sytomArr)
self.idArr.addObject(idArray)
}
self.saveWithFile()
self.bodyTableView.reloadData()
for var x=0;x<self.dataArr.count;x++
{
if self.position != nil
{
var model=self.dataArr.objectAtIndex(x)as!PositionModel
if model.jbname==self.position
{
self.index=x
self.bodyString=model.jbname
}
}else
{
var model=self.dataArr.objectAtIndex(0)as!PositionModel
self.bodyString=model.jbname
}
}
var indexPath=NSIndexPath(forRow: self.index, inSection: 0)
var array:NSArray=[indexPath]
self.bodyTableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.Middle)
self.symptomTableView.reloadData()
self.bgView.removeFromSuperview()
self.activity.stopAnimating()
UIApplication.sharedApplication().networkActivityIndicatorVisible=false
}
}
func initData()
{
symptomArray=NSMutableArray()
bodyArray=NSMutableArray()
//
var manPath=NSBundle.mainBundle().pathForResource("TCLMan", ofType: "plist")
var woManPath=NSBundle.mainBundle().pathForResource("TCLWoman", ofType: "plist")
var kidPath=NSBundle.mainBundle().pathForResource("TCLChild", ofType: "plist")
var manArr:NSMutableArray=NSMutableArray()
if typeNum==1
{
manArr=NSMutableArray(contentsOfFile: manPath!)!
}else if typeNum==2
{
manArr=NSMutableArray(contentsOfFile: woManPath!)!
}else if typeNum==3
{
manArr=NSMutableArray(contentsOfFile: kidPath!)!
}
for var i=0;i<manArr.count;i++
{
var symptomDic: NSDictionary=manArr.objectAtIndex(i) as! NSDictionary
var symptomArr: AnyObject?=symptomDic.objectForKey("arr")
var bodyString: AnyObject?=symptomDic.objectForKey("first")
bodyArray.addObject(bodyString!)
var array=NSMutableArray()
for var j=0;j<symptomArr?.count;j++
{
var dic: AnyObject=symptomArr!.objectAtIndex(j)
var model=SymptomModel()
model.setValuesForKeysWithDictionary(dic as! [NSObject : AnyObject])
array.addObject(model)
}
symptomArray.addObject(array)
}
}
func createUI()
{
self.bgView=UIView(frame: CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT))
self.bgView.backgroundColor=UIColor.grayColor()
self.bgView.alpha=0.5
self.activity=UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
self.activity.frame=CGRectMake(IPHONE_WIDTH/2-50, IPHONE_HEIGHT/2-50-64, 100, 100)
self.activity.backgroundColor=UIColor.blackColor()
self.bgView.addSubview(self.activity)
self.tabBarController?.tabBar.userInteractionEnabled=true
self.navigationItem.title="症状列表";
var backButton:UIButton=UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
backButton.frame=CGRectMake(0, 0, 40, 40)
backButton.tag=100
backButton.setImage(UIImage(named: "back"), forState: UIControlState.Normal)
self.navigationItem.leftBarButtonItem=UIBarButtonItem(customView: backButton)
backButton.addTarget(self, action: Selector("btnClick:"), forControlEvents: UIControlEvents.TouchUpInside)
index=0
var width:CGFloat=100.0;
if IPHONE_HEIGHT==480
{
width=120.0
bodyTableView=UITableView(frame: CGRectMake(0, 0, width, IPHONE_HEIGHT-64), style:UITableViewStyle.Plain)
}else if IPHONE_HEIGHT==568
{
width=120.0
bodyTableView=UITableView(frame: CGRectMake(0, 0, width, IPHONE_HEIGHT-64), style:UITableViewStyle.Plain)
}else if IPHONE_HEIGHT==667
{
width=140
bodyTableView=UITableView(frame: CGRectMake(0, 0, width, IPHONE_HEIGHT-64), style:UITableViewStyle.Plain)
}else
{
width=160
bodyTableView=UITableView(frame: CGRectMake(0, 0, width, IPHONE_HEIGHT-64), style:UITableViewStyle.Plain)
}
bodyTableView.separatorStyle=UITableViewCellSeparatorStyle.None
bodyTableView.delegate=self
bodyTableView.dataSource=self
bodyTableView.showsVerticalScrollIndicator=false
self.view.addSubview(bodyTableView)
symptomTableView=UITableView(frame: CGRectMake(width, 0, IPHONE_WIDTH-width, IPHONE_HEIGHT-64), style: UITableViewStyle.Plain)
symptomTableView.separatorStyle=UITableViewCellSeparatorStyle.None
symptomTableView.delegate=self
symptomTableView.showsVerticalScrollIndicator=false
symptomTableView.dataSource=self
self.view.addSubview(symptomTableView)
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if tableView==bodyTableView
{
return 106
}else
{
return 106
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView==bodyTableView
{
if dataArr.count==0
{
if bodyArr.count != 0
{
return bodyArr.count
}
return 0
}else
{
return dataArr.count
}
}else
{
if self.dataArr.count != 0
{
var model=self.dataArr.objectAtIndex(index)as! PositionModel
return model.jblistArr.count
}else
{
if nameArr.count != 0
{
return nameArr.objectAtIndex(index).count
}
return 0
}
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView==bodyTableView
{
index=indexPath.row
symptomTableView.reloadData()
if dataArr.count == 0
{
self.bodyString=self.bodyArr.objectAtIndex(indexPath.row) as! String
}else
{
var model=self.dataArr.objectAtIndex(indexPath.row) as! PositionModel
self.bodyString=model.jbname
}
}else
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var guide:GuideViewController=GuideViewController()
guide.personType=self.personType
if dataArr.count != 0
{
var posiModel=self.dataArr.objectAtIndex(index) as!PositionModel
println(self.symptomArray.count)
var array:NSArray=self.symptomArray.objectAtIndex(index) as! NSArray
var model=posiModel.jblistArr.objectAtIndex(indexPath.row) as!JBModel
guide.bodyType=self.bodyString
guide.symptomType=model.jbname
guide.id=model.id
}else
{
guide.bodyType=self.bodyString
guide.symptomType=nameArr.objectAtIndex(index).objectAtIndex(indexPath.row) as! String
guide.id=idArr.objectAtIndex(index).objectAtIndex(indexPath.row) as! String
}
self.navigationController?.pushViewController(guide, animated: true)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView==bodyTableView
{
var cell: UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
var bgViwe=UIImageView()
bgViwe.image=UIImage(named: "cell")
cell.backgroundView=bgViwe
if dataArr.count != 0
{
var model=self.dataArr.objectAtIndex(indexPath.row)as!PositionModel
cell.textLabel?.text=model.jbname
}else
{
cell.textLabel?.text=bodyArr.objectAtIndex(indexPath.row) as? String
}
return cell
}else
{
var cell: UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
if dataArr.count != 0
{
var posiModel=self.dataArr.objectAtIndex(index)as! PositionModel
var model=posiModel.jblistArr.objectAtIndex(indexPath.row) as!JBModel
cell.textLabel?.text=model.jbname
}else
{
cell.textLabel?.text=nameArr.objectAtIndex(index).objectAtIndex(indexPath.row) as? String
}
return cell
}
}
func btnClick(sender:UIButton)
{
var tag:NSInteger=sender.tag
switch tag
{
case 100:
self.navigationController?.popViewControllerAnimated(true)
default :
return
}
}
func saveWithFile() {
/// 1、获得沙盒的根路径
let home = NSHomeDirectory() as NSString;
/// 2、获得Documents路径,使用NSString对象的stringByAppendingPathComponent()方法拼接路径
let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
/// 3、获取文本文件路径
let filePath = docPath.stringByAppendingPathComponent("data.plist");
let namePath=docPath.stringByAppendingPathComponent("name.plist")
let idPath=docPath.stringByAppendingPathComponent("id.plist")
var dataSource = NSMutableArray();
dataSource.addObject("衣带渐宽终不悔");
dataSource.addObject("为伊消得人憔悴");
dataSource.addObject("故国不堪回首明月中");
dataSource.addObject("人生若只如初见");
dataSource.addObject("暮然回首,那人却在灯火阑珊处");
// 4、将数据写入文件中
//dataSource.writeToFile(filePath, atomically: true);
self.bodyArr.writeToFile(filePath, atomically: true)
self.nameArr.writeToFile(namePath, atomically: true)
self.idArr.writeToFile(idPath, atomically: true)
}
func readWithFile() {
/// 1、获得沙盒的根路径
let home = NSHomeDirectory() as NSString;
/// 2、获得Documents路径,使用NSString对象的stringByAppendingPathComponent()方法拼接路径
let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
/// 3、获取文本文件路径
let filePath = docPath.stringByAppendingPathComponent("data.plist");
let namePath=docPath.stringByAppendingPathComponent("name.plist")
let idPath=docPath.stringByAppendingPathComponent("id.plist")
let dataSource:NSArray = NSArray(contentsOfFile: filePath)!;
self.bodyArr=NSMutableArray()
for str in dataSource
{
self.bodyArr.addObject(str)
}
let nameSource:NSArray = NSArray(contentsOfFile: namePath)!
self.nameArr=NSMutableArray()
for str in nameSource
{
self.nameArr.addObject(str)
}
let idSource:NSArray = NSArray(contentsOfFile: idPath)!
self.idArr=NSMutableArray(object: idSource)
for str in idSource
{
self.idArr.addObject(str)
}
//self.dataArr=NSMutableArray(array: dataSource)
self.bodyTableView.reloadData()
for var x=0;x<self.bodyArr.count;x++
{
if self.position != nil
{
var str=self.bodyArr.objectAtIndex(x)as!String
if str==self.position
{
self.index=x
self.bodyString=str
}
}else
{
var model=self.bodyArr.objectAtIndex(0)as!String
self.bodyString=model
}
}
var indexPath=NSIndexPath(forRow: self.index, inSection: 0)
var array:NSArray=[indexPath]
self.bodyTableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.Middle)
self.symptomTableView.reloadData()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-2.0
|
d52fdc21d2504da96cb40703fa373f88
| 35.01217 | 201 | 0.582066 | 5.085649 | false | false | false | false |
apple/swift
|
test/Generics/issue-53142.swift
|
2
|
594
|
// RUN: %target-typecheck-verify-swift -debug-generic-signatures -warn-redundant-requirements 2>&1 | %FileCheck %s
// https://github.com/apple/swift/issues/53142
// CHECK-LABEL: .P@
// CHECK-NEXT: Requirement signature: <Self where Self.[P]A : P, Self.[P]A == Self.[P]A.[P]A>
protocol P {
associatedtype A : P where A.A == A
}
// CHECK-LABEL: .Q@
// CHECK-NEXT: Requirement signature: <Self where Self.[Q]A == Self.[Q]C.[P]A, Self.[Q]C : P>
protocol Q {
associatedtype A : P // expected-warning {{redundant conformance constraint 'Self.A' : 'P'}}
associatedtype C : P where A == C.A
}
|
apache-2.0
|
df5a53c247e9140323bb3323480c7cf9
| 36.125 | 114 | 0.666667 | 3.015228 | false | false | false | false |
xichen744/SPPage
|
Swift/SPPage/core/SPCoverController.swift
|
1
|
2581
|
//
// SPCoverController.swift
// SPPage
//
// Created by GodDan on 2018/3/11.
// Copyright © 2018年 GodDan. All rights reserved.
//
import UIKit
enum CoverScrollStyle {
case height
case top
}
class SPCoverController: SPTabController,SPCoverDataSource {
private var coverView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
self.loadCoverView()
}
func preferCoverStyle() -> CoverScrollStyle {
return .height
}
private func reloadCoverView() {
self.coverView?.removeFromSuperview()
self.loadCoverView()
}
override func reloadData() {
super.reloadData()
self.reloadCoverView()
}
private func loadCoverView() {
if let coverView = self.preferCoverView() {
coverView.frame = self.preferCoverFrame()
self.view.addSubview(coverView)
self.coverView = coverView
}
}
//SPCoverProtocol
func preferCoverView() -> UIView? {
return nil
}
func preferCoverFrame() -> CGRect {
return CGRect()
}
// SPPageControllerDelegate
override func scrollWithPageOffset(pageOffset: CGFloat, index: NSInteger) {
super.scrollWithPageOffset(pageOffset: pageOffset, index: index)
let top = self.tabScrollTopWithContentOffset(offset: pageOffset + self.pageTopAtIndex(index: index))
let realOffset = self.preferTabFrame(index: index).origin.y - top
if self.preferCoverStyle() == .height {
let coverHeight = self.preferCoverFrame().size.height - realOffset
if coverHeight >= 0 {
coverView?.frame.size.height = coverHeight
} else {
coverView?.frame.size.height = 0
}
} else {
let coverTop = self.preferCoverFrame().origin.y - realOffset
if coverTop >= self.preferCoverFrame().origin.y - self.preferCoverFrame().size.height {
coverView?.frame.origin.y = coverTop
} else {
coverView?.frame.origin.y = self.preferCoverFrame().origin.y - self.preferCoverFrame().size.height
}
}
}
// SPPageControllerDataSource
override func pageTopAtIndex(index: NSInteger) -> CGFloat {
let pageTop = super.pageTopAtIndex(index: index)
let coverPageTop = self.preferCoverFrame().origin.y + self.preferCoverFrame().size.height
return pageTop > coverPageTop ? pageTop :coverPageTop
}
}
|
mit
|
29bfbf7ce5fbba9844a391adfcf460b1
| 27.966292 | 114 | 0.609775 | 4.611807 | false | false | false | false |
lorentey/swift
|
stdlib/public/core/LegacyABI.swift
|
6
|
2544
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file contains non-API (or underscored) declarations that are needed to
// be kept around for ABI compatibility
extension Unicode.UTF16 {
@available(*, unavailable, renamed: "Unicode.UTF16.isASCII")
@inlinable
public static func _isASCII(_ x: CodeUnit) -> Bool {
return Unicode.UTF16.isASCII(x)
}
}
@available(*, unavailable, renamed: "Unicode.UTF8.isASCII")
@inlinable
internal func _isASCII(_ x: UInt8) -> Bool {
return Unicode.UTF8.isASCII(x)
}
@available(*, unavailable, renamed: "Unicode.UTF8.isContinuation")
@inlinable
internal func _isContinuation(_ x: UInt8) -> Bool {
return UTF8.isContinuation(x)
}
extension Substring {
@available(*, unavailable, renamed: "Substring.base")
@inlinable
internal var _wholeString: String { return base }
}
extension String {
@available(*, unavailable, renamed: "String.withUTF8")
@inlinable
internal func _withUTF8<R>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R {
var copy = self
return try copy.withUTF8(body)
}
}
extension Substring {
@available(*, unavailable, renamed: "Substring.withUTF8")
@inlinable
internal func _withUTF8<R>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R {
var copy = self
return try copy.withUTF8(body)
}
}
// This function is no longer used but must be kept for ABI compatibility
// because references to it may have been inlined.
@usableFromInline
internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool {
// The LLVM intrinsic underlying int_expect_Int1 now requires an immediate
// argument for the expected value so we cannot call it here. This should
// never be called in cases where performance matters, so just return the
// value without any branch hint.
return actual
}
extension String {
@usableFromInline // Never actually used in inlinable code...
internal func _nativeCopyUTF16CodeUnits(
into buffer: UnsafeMutableBufferPointer<UInt16>,
range: Range<String.Index>
) { fatalError() }
}
|
apache-2.0
|
0046ab3c1026ba65883d5a451f3f2885
| 30.407407 | 80 | 0.674528 | 4.232945 | false | false | false | false |
byu-oit/ios-byuSuite
|
byuSuite/Apps/MyFinancialCenter/controller/MFCPaymentDetailViewController.swift
|
2
|
1449
|
//
// MFCPaymentDetailViewController.swift
// byuSuite
//
// Created by Erik Brady on 5/10/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import UIKit
private let TABLE_FOOTER_TEXT = "No Charges Found"
class MFCPaymentDetailViewController: ByuTableDataViewController {
//MARK: Properties
var chargesAppliedTo = [MFCCharge]()
override func viewDidLoad() {
super.viewDidLoad()
if chargesAppliedTo.count == 0 {
tableData = TableData()
} else {
tableData = TableData(rows: chargesAppliedTo.map { return Row(enabled: false, object: $0) })
}
tableView.variableHeightForRows()
tableView.registerNib(nibName: "MFCTransactionTableViewCell")
}
//MARK: ByuTableDataViewController Methods
override func getEmptyTableViewText() -> String {
return TABLE_FOOTER_TEXT
}
//MARK: UITableViewDataSource/Delegate Methods
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableData.dequeueCell(forTableView: tableView, atIndexPath: indexPath) as? MFCTransactionTableViewCell,
let charge = tableData.row(forIndexPath: indexPath).object as? MFCCharge {
cell.transaction = charge
return cell
} else { return UITableViewCell() }
}
}
|
apache-2.0
|
a535e991bf8d7da6badf1bf7bb176ee5
| 27.96 | 125 | 0.654696 | 4.826667 | false | false | false | false |
alblue/swift
|
test/stdlib/RuntimeObjC.swift
|
1
|
23389
|
// RUN: %empty-directory(%t)
//
// RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g
// RUN: %target-build-swift -parse-stdlib -Xfrontend -disable-access-control -module-name a -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o %s -o %t.out
// RUN: %target-codesign %t.out
// RUN: %target-run %t.out
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Swift
import StdlibUnittest
import Foundation
import CoreGraphics
import SwiftShims
import MirrorObjC
var nsObjectCanaryCount = 0
@objc class NSObjectCanary : NSObject {
override init() {
nsObjectCanaryCount += 1
}
deinit {
nsObjectCanaryCount -= 1
}
}
struct NSObjectCanaryStruct {
var ref = NSObjectCanary()
}
var swiftObjectCanaryCount = 0
class SwiftObjectCanary {
init() {
swiftObjectCanaryCount += 1
}
deinit {
swiftObjectCanaryCount -= 1
}
}
struct SwiftObjectCanaryStruct {
var ref = SwiftObjectCanary()
}
@objc class ClassA {
init(value: Int) {
self.value = value
}
var value: Int
}
struct BridgedValueType : _ObjectiveCBridgeable {
init(value: Int) {
self.value = value
}
func _bridgeToObjectiveC() -> ClassA {
return ClassA(value: value)
}
static func _forceBridgeFromObjectiveC(
_ x: ClassA,
result: inout BridgedValueType?
) {
assert(x.value % 2 == 0, "not bridged to Objective-C")
result = BridgedValueType(value: x.value)
}
static func _conditionallyBridgeFromObjectiveC(
_ x: ClassA,
result: inout BridgedValueType?
) -> Bool {
if x.value % 2 == 0 {
result = BridgedValueType(value: x.value)
return true
}
result = nil
return false
}
static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?)
-> BridgedValueType {
var result: BridgedValueType?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
var value: Int
var canaryRef = SwiftObjectCanary()
}
struct BridgedLargeValueType : _ObjectiveCBridgeable {
init(value: Int) {
value0 = value
value1 = value
value2 = value
value3 = value
value4 = value
value5 = value
value6 = value
value7 = value
}
func _bridgeToObjectiveC() -> ClassA {
assert(value == value0)
return ClassA(value: value0)
}
static func _forceBridgeFromObjectiveC(
_ x: ClassA,
result: inout BridgedLargeValueType?
) {
assert(x.value % 2 == 0, "not bridged to Objective-C")
result = BridgedLargeValueType(value: x.value)
}
static func _conditionallyBridgeFromObjectiveC(
_ x: ClassA,
result: inout BridgedLargeValueType?
) -> Bool {
if x.value % 2 == 0 {
result = BridgedLargeValueType(value: x.value)
return true
}
result = nil
return false
}
static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?)
-> BridgedLargeValueType {
var result: BridgedLargeValueType?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
var value: Int {
let x = value0
assert(value0 == x && value1 == x && value2 == x && value3 == x &&
value4 == x && value5 == x && value6 == x && value7 == x)
return x
}
var (value0, value1, value2, value3): (Int, Int, Int, Int)
var (value4, value5, value6, value7): (Int, Int, Int, Int)
var canaryRef = SwiftObjectCanary()
}
class BridgedVerbatimRefType {
var value: Int = 42
var canaryRef = SwiftObjectCanary()
}
func withSwiftObjectCanary<T>(
_ createValue: () -> T,
_ check: (T) -> Void,
file: String = #file, line: UInt = #line
) {
let stackTrace = SourceLocStack(SourceLoc(file, line))
swiftObjectCanaryCount = 0
autoreleasepool {
var valueWithCanary = createValue()
expectEqual(1, swiftObjectCanaryCount, stackTrace: stackTrace)
check(valueWithCanary)
}
expectEqual(0, swiftObjectCanaryCount, stackTrace: stackTrace)
}
var Runtime = TestSuite("Runtime")
func _isClassOrObjCExistential_Opaque<T>(_ x: T.Type) -> Bool {
return _isClassOrObjCExistential(_opaqueIdentity(x))
}
Runtime.test("_isClassOrObjCExistential") {
expectTrue(_isClassOrObjCExistential(NSObjectCanary.self))
expectTrue(_isClassOrObjCExistential_Opaque(NSObjectCanary.self))
expectFalse(_isClassOrObjCExistential(NSObjectCanaryStruct.self))
expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanaryStruct.self))
expectTrue(_isClassOrObjCExistential(SwiftObjectCanary.self))
expectTrue(_isClassOrObjCExistential_Opaque(SwiftObjectCanary.self))
expectFalse(_isClassOrObjCExistential(SwiftObjectCanaryStruct.self))
expectFalse(_isClassOrObjCExistential_Opaque(SwiftObjectCanaryStruct.self))
typealias SwiftClosure = () -> ()
expectFalse(_isClassOrObjCExistential(SwiftClosure.self))
expectFalse(_isClassOrObjCExistential_Opaque(SwiftClosure.self))
typealias ObjCClosure = @convention(block) () -> ()
expectTrue(_isClassOrObjCExistential(ObjCClosure.self))
expectTrue(_isClassOrObjCExistential_Opaque(ObjCClosure.self))
expectTrue(_isClassOrObjCExistential(CFArray.self))
expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self))
expectTrue(_isClassOrObjCExistential(CFArray.self))
expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self))
expectTrue(_isClassOrObjCExistential(AnyObject.self))
expectTrue(_isClassOrObjCExistential_Opaque(AnyObject.self))
// AnyClass == AnyObject.Type
expectFalse(_isClassOrObjCExistential(AnyClass.self))
expectFalse(_isClassOrObjCExistential_Opaque(AnyClass.self))
expectFalse(_isClassOrObjCExistential(AnyObject.Protocol.self))
expectFalse(_isClassOrObjCExistential_Opaque(AnyObject.Protocol.self))
expectFalse(_isClassOrObjCExistential(NSObjectCanary.Type.self))
expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanary.Type.self))
}
Runtime.test("_canBeClass") {
expectEqual(1, _canBeClass(NSObjectCanary.self))
expectEqual(0, _canBeClass(NSObjectCanaryStruct.self))
typealias ObjCClosure = @convention(block) () -> ()
expectEqual(1, _canBeClass(ObjCClosure.self))
expectEqual(1, _canBeClass(CFArray.self))
}
Runtime.test("bridgeToObjectiveC") {
expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedValueType(value: 42)) as! ClassA).value)
expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedLargeValueType(value: 42)) as! ClassA).value)
var bridgedVerbatimRef = BridgedVerbatimRefType()
expectTrue(_bridgeAnythingToObjectiveC(bridgedVerbatimRef) === bridgedVerbatimRef)
}
Runtime.test("bridgeToObjectiveC/NoLeak") {
withSwiftObjectCanary(
{ BridgedValueType(value: 42) },
{ expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) })
withSwiftObjectCanary(
{ BridgedLargeValueType(value: 42) },
{ expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) })
withSwiftObjectCanary(
{ BridgedVerbatimRefType() },
{ expectTrue(_bridgeAnythingToObjectiveC($0) === $0) })
}
Runtime.test("forceBridgeFromObjectiveC") {
// Bridge back using BridgedValueType.
expectNil(_conditionallyBridgeFromObjectiveC(
ClassA(value: 21), BridgedValueType.self))
expectEqual(42, _forceBridgeFromObjectiveC(
ClassA(value: 42), BridgedValueType.self).value)
expectEqual(42, _conditionallyBridgeFromObjectiveC(
ClassA(value: 42), BridgedValueType.self)!.value)
expectNil(_conditionallyBridgeFromObjectiveC(
BridgedVerbatimRefType(), BridgedValueType.self))
// Bridge back using BridgedLargeValueType.
expectNil(_conditionallyBridgeFromObjectiveC(
ClassA(value: 21), BridgedLargeValueType.self))
expectEqual(42, _forceBridgeFromObjectiveC(
ClassA(value: 42), BridgedLargeValueType.self).value)
expectEqual(42, _conditionallyBridgeFromObjectiveC(
ClassA(value: 42), BridgedLargeValueType.self)!.value)
expectNil(_conditionallyBridgeFromObjectiveC(
BridgedVerbatimRefType(), BridgedLargeValueType.self))
// Bridge back using BridgedVerbatimRefType.
expectNil(_conditionallyBridgeFromObjectiveC(
ClassA(value: 21), BridgedVerbatimRefType.self))
expectNil(_conditionallyBridgeFromObjectiveC(
ClassA(value: 42), BridgedVerbatimRefType.self))
var bridgedVerbatimRef = BridgedVerbatimRefType()
expectTrue(_forceBridgeFromObjectiveC(
bridgedVerbatimRef, BridgedVerbatimRefType.self) === bridgedVerbatimRef)
expectTrue(_conditionallyBridgeFromObjectiveC(
bridgedVerbatimRef, BridgedVerbatimRefType.self)! === bridgedVerbatimRef)
}
Runtime.test("isBridgedToObjectiveC") {
expectTrue(_isBridgedToObjectiveC(BridgedValueType.self))
expectTrue(_isBridgedToObjectiveC(BridgedVerbatimRefType.self))
}
Runtime.test("isBridgedVerbatimToObjectiveC") {
expectFalse(_isBridgedVerbatimToObjectiveC(BridgedValueType.self))
expectTrue(_isBridgedVerbatimToObjectiveC(BridgedVerbatimRefType.self))
}
//===----------------------------------------------------------------------===//
class SomeClass {}
@objc class SomeObjCClass {}
class SomeNSObjectSubclass : NSObject {}
Runtime.test("typeName") {
expectEqual("a.SomeObjCClass", _typeName(SomeObjCClass.self))
expectEqual("a.SomeNSObjectSubclass", _typeName(SomeNSObjectSubclass.self))
expectEqual("NSObject", _typeName(NSObject.self))
var a : Any = SomeObjCClass()
expectEqual("a.SomeObjCClass", _typeName(type(of: a)))
a = SomeNSObjectSubclass()
expectEqual("a.SomeNSObjectSubclass", _typeName(type(of: a)))
a = NSObject()
expectEqual("NSObject", _typeName(type(of: a)))
}
class GenericClass<T> {}
class MultiGenericClass<T, U> {}
struct GenericStruct<T> {}
enum GenericEnum<T> {}
struct PlainStruct {}
enum PlainEnum {}
protocol ProtocolA {}
protocol ProtocolB {}
Runtime.test("Generic class ObjC runtime names") {
expectEqual("_TtGC1a12GenericClassSi_",
NSStringFromClass(GenericClass<Int>.self))
expectEqual("_TtGC1a12GenericClassVS_11PlainStruct_",
NSStringFromClass(GenericClass<PlainStruct>.self))
expectEqual("_TtGC1a12GenericClassOS_9PlainEnum_",
NSStringFromClass(GenericClass<PlainEnum>.self))
expectEqual("_TtGC1a12GenericClassTVS_11PlainStructOS_9PlainEnumS1___",
NSStringFromClass(GenericClass<(PlainStruct, PlainEnum, PlainStruct)>.self))
expectEqual("_TtGC1a12GenericClassMVS_11PlainStruct_",
NSStringFromClass(GenericClass<PlainStruct.Type>.self))
expectEqual("_TtGC1a12GenericClassFMVS_11PlainStructS1__",
NSStringFromClass(GenericClass<(PlainStruct.Type) -> PlainStruct>.self))
expectEqual("_TtGC1a12GenericClassFzMVS_11PlainStructS1__",
NSStringFromClass(GenericClass<(PlainStruct.Type) throws -> PlainStruct>.self))
expectEqual("_TtGC1a12GenericClassFTVS_11PlainStructROS_9PlainEnum_Si_",
NSStringFromClass(GenericClass<(PlainStruct, inout PlainEnum) -> Int>.self))
expectEqual("_TtGC1a12GenericClassPS_9ProtocolA__",
NSStringFromClass(GenericClass<ProtocolA>.self))
expectEqual("_TtGC1a12GenericClassPS_9ProtocolAS_9ProtocolB__",
NSStringFromClass(GenericClass<ProtocolA & ProtocolB>.self))
expectEqual("_TtGC1a12GenericClassPMPS_9ProtocolAS_9ProtocolB__",
NSStringFromClass(GenericClass<(ProtocolA & ProtocolB).Type>.self))
expectEqual("_TtGC1a12GenericClassMPS_9ProtocolAS_9ProtocolB__",
NSStringFromClass(GenericClass<(ProtocolB & ProtocolA).Protocol>.self))
expectEqual("_TtGC1a12GenericClassaSo10CFArrayRef_",
NSStringFromClass(GenericClass<CFArray>.self))
expectEqual("_TtGC1a12GenericClassaSo9NSDecimal_",
NSStringFromClass(GenericClass<Decimal>.self))
expectEqual("_TtGC1a12GenericClassCSo8NSObject_",
NSStringFromClass(GenericClass<NSObject>.self))
expectEqual("_TtGC1a12GenericClassCSo8NSObject_",
NSStringFromClass(GenericClass<NSObject>.self))
expectEqual("_TtGC1a12GenericClassPSo9NSCopying__",
NSStringFromClass(GenericClass<NSCopying>.self))
expectEqual("_TtGC1a12GenericClassPSo9NSCopyingS_9ProtocolAS_9ProtocolB__",
NSStringFromClass(GenericClass<ProtocolB & NSCopying & ProtocolA>.self))
expectEqual("_TtGC1a12GenericClassXcCS_9SomeClassS_9ProtocolA__",
NSStringFromClass(GenericClass<ProtocolA & SomeClass>.self))
expectEqual("_TtGC1a12GenericClassPS_9ProtocolAs9AnyObject__",
NSStringFromClass(GenericClass<ProtocolA & AnyObject>.self))
expectEqual("_TtGC1a12GenericClassPs9AnyObject__",
NSStringFromClass(GenericClass<AnyObject>.self))
expectEqual("_TtGC1a17MultiGenericClassGVS_13GenericStructSi_GOS_11GenericEnumGS2_Si___",
NSStringFromClass(MultiGenericClass<GenericStruct<Int>,
GenericEnum<GenericEnum<Int>>>.self))
}
@objc protocol P {}
struct AnyObjStruct<T: AnyObject> {}
Runtime.test("typeByName") {
// Make sure we don't crash if we have foreign classes in the
// table -- those don't have NominalTypeDescriptors
print(CFArray.self)
expectTrue(_typeByName("a.SomeClass") == SomeClass.self)
expectTrue(_typeByName("DoesNotExist") == nil)
expectTrue(_typeByName("1a12AnyObjStructVyAA1P_pG") == AnyObjStruct<P>.self)
}
Runtime.test("casting AnyObject to class metatypes") {
do {
var ao: AnyObject = SomeClass.self
expectTrue(ao as? Any.Type == SomeClass.self)
expectTrue(ao as? AnyClass == SomeClass.self)
expectTrue(ao as? SomeClass.Type == SomeClass.self)
}
do {
var ao : AnyObject = SomeNSObjectSubclass()
expectTrue(ao as? Any.Type == nil)
expectTrue(ao as? AnyClass == nil)
ao = SomeNSObjectSubclass.self
expectTrue(ao as? Any.Type == SomeNSObjectSubclass.self)
expectTrue(ao as? AnyClass == SomeNSObjectSubclass.self)
expectTrue(ao as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self)
}
do {
var a : Any = SomeNSObjectSubclass()
expectTrue(a as? Any.Type == nil)
expectTrue(a as? AnyClass == nil)
}
do {
var nso: NSObject = SomeNSObjectSubclass()
expectTrue(nso as? AnyClass == nil)
nso = (SomeNSObjectSubclass.self as AnyObject) as! NSObject
expectTrue(nso as? Any.Type == SomeNSObjectSubclass.self)
expectTrue(nso as? AnyClass == SomeNSObjectSubclass.self)
expectTrue(nso as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self)
}
}
var RuntimeFoundationWrappers = TestSuite("RuntimeFoundationWrappers")
RuntimeFoundationWrappers.test("_stdlib_NSObject_isEqual/NoLeak") {
nsObjectCanaryCount = 0
autoreleasepool {
let a = NSObjectCanary()
let b = NSObjectCanary()
expectEqual(2, nsObjectCanaryCount)
_stdlib_NSObject_isEqual(a, b)
}
expectEqual(0, nsObjectCanaryCount)
}
var nsStringCanaryCount = 0
@objc class NSStringCanary : NSString {
override init() {
nsStringCanaryCount += 1
super.init()
}
required init(coder: NSCoder) {
fatalError("don't call this initializer")
}
required init(itemProviderData data: Data, typeIdentifier: String) throws {
fatalError("don't call this initializer")
}
deinit {
nsStringCanaryCount -= 1
}
@objc override var length: Int {
return 0
}
@objc override func character(at index: Int) -> unichar {
fatalError("out-of-bounds access")
}
}
RuntimeFoundationWrappers.test("_stdlib_CFStringCreateCopy/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_binary_CFStringCreateCopy(a)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_CFStringGetLength/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_binary_CFStringGetLength(a)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_CFStringGetCharactersPtr/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_binary_CFStringGetCharactersPtr(a)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("bridgedNSArray") {
var c = [NSObject]()
autoreleasepool {
let a = [NSObject]()
let b = a as NSArray
c = b as! [NSObject]
}
c.append(NSObject())
// expect no crash.
}
var Reflection = TestSuite("Reflection")
class SwiftFooMoreDerivedObjCClass : FooMoreDerivedObjCClass {
let first: Int = 123
let second: String = "abc"
}
Reflection.test("Class/ObjectiveCBase/Default") {
do {
let value = SwiftFooMoreDerivedObjCClass()
var output = ""
dump(value, to: &output)
let expected =
"▿ This is FooObjCClass #0\n" +
" - super: FooMoreDerivedObjCClass\n" +
" - super: FooDerivedObjCClass\n" +
" - super: FooObjCClass\n" +
" - super: NSObject\n" +
" - first: 123\n" +
" - second: \"abc\"\n"
expectEqual(expected, output)
}
}
protocol SomeNativeProto {}
@objc protocol SomeObjCProto {}
extension SomeClass: SomeObjCProto {}
Reflection.test("MetatypeMirror") {
do {
let concreteClassMetatype = SomeClass.self
let expectedSomeClass = "- a.SomeClass #0\n"
let objcProtocolMetatype: SomeObjCProto.Type = SomeClass.self
var output = ""
dump(objcProtocolMetatype, to: &output)
expectEqual(expectedSomeClass, output)
let objcProtocolConcreteMetatype = SomeObjCProto.self
let expectedObjCProtocolConcrete = "- a.SomeObjCProto #0\n"
output = ""
dump(objcProtocolConcreteMetatype, to: &output)
expectEqual(expectedObjCProtocolConcrete, output)
let compositionConcreteMetatype = (SomeNativeProto & SomeObjCProto).self
let expectedComposition = "- a.SomeNativeProto & a.SomeObjCProto #0\n"
output = ""
dump(compositionConcreteMetatype, to: &output)
expectEqual(expectedComposition, output)
let objcDefinedProtoType = NSObjectProtocol.self
expectEqual(String(describing: objcDefinedProtoType), "NSObject")
}
}
Reflection.test("CGPoint") {
var output = ""
dump(CGPoint(x: 1.25, y: 2.75), to: &output)
let expected =
"▿ (1.25, 2.75)\n" +
" - x: 1.25\n" +
" - y: 2.75\n"
expectEqual(expected, output)
}
Reflection.test("CGSize") {
var output = ""
dump(CGSize(width: 1.25, height: 2.75), to: &output)
let expected =
"▿ (1.25, 2.75)\n" +
" - width: 1.25\n" +
" - height: 2.75\n"
expectEqual(expected, output)
}
Reflection.test("CGRect") {
var output = ""
dump(
CGRect(
origin: CGPoint(x: 1.25, y: 2.25),
size: CGSize(width: 10.25, height: 11.75)),
to: &output)
let expected =
"▿ (1.25, 2.25, 10.25, 11.75)\n" +
" ▿ origin: (1.25, 2.25)\n" +
" - x: 1.25\n" +
" - y: 2.25\n" +
" ▿ size: (10.25, 11.75)\n" +
" - width: 10.25\n" +
" - height: 11.75\n"
expectEqual(expected, output)
}
Reflection.test("Unmanaged/nil") {
var output = ""
var optionalURL: Unmanaged<CFURL>?
dump(optionalURL, to: &output)
let expected = "- nil\n"
expectEqual(expected, output)
}
Reflection.test("Unmanaged/not-nil") {
var output = ""
var optionalURL: Unmanaged<CFURL>? =
Unmanaged.passRetained(CFURLCreateWithString(nil, "http://llvm.org/" as CFString, nil))
dump(optionalURL, to: &output)
let expected =
"▿ Optional(Swift.Unmanaged<__C.CFURLRef>(_value: http://llvm.org/))\n" +
" ▿ some: Swift.Unmanaged<__C.CFURLRef>\n" +
" - _value: http://llvm.org/ #0\n" +
" - super: NSObject\n"
expectEqual(expected, output)
optionalURL!.release()
}
Reflection.test("TupleMirror/NoLeak") {
do {
nsObjectCanaryCount = 0
autoreleasepool {
var tuple = (1, NSObjectCanary())
expectEqual(1, nsObjectCanaryCount)
var output = ""
dump(tuple, to: &output)
}
expectEqual(0, nsObjectCanaryCount)
}
do {
nsObjectCanaryCount = 0
autoreleasepool {
var tuple = (1, NSObjectCanaryStruct())
expectEqual(1, nsObjectCanaryCount)
var output = ""
dump(tuple, to: &output)
}
expectEqual(0, nsObjectCanaryCount)
}
do {
swiftObjectCanaryCount = 0
autoreleasepool {
var tuple = (1, SwiftObjectCanary())
expectEqual(1, swiftObjectCanaryCount)
var output = ""
dump(tuple, to: &output)
}
expectEqual(0, swiftObjectCanaryCount)
}
do {
swiftObjectCanaryCount = 0
autoreleasepool {
var tuple = (1, SwiftObjectCanaryStruct())
expectEqual(1, swiftObjectCanaryCount)
var output = ""
dump(tuple, to: &output)
}
expectEqual(0, swiftObjectCanaryCount)
}
}
@objc @objcMembers class TestArtificialSubclass: NSObject {
dynamic var foo = "foo"
}
var KVOHandle = 0
Reflection.test("Name of metatype of artificial subclass") {
let obj = TestArtificialSubclass()
expectEqual("\(type(of: obj))", "TestArtificialSubclass")
expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass")
expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass")
// Trigger the creation of a KVO subclass for TestArtificialSubclass.
obj.addObserver(obj, forKeyPath: "foo", options: [.new], context: &KVOHandle)
expectEqual("\(type(of: obj))", "TestArtificialSubclass")
expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass")
expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass")
obj.removeObserver(obj, forKeyPath: "foo")
expectEqual("\(type(of: obj))", "TestArtificialSubclass")
expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass")
expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass")
}
@objc class StringConvertibleInDebugAndOtherwise : NSObject {
override var description: String { return "description" }
override var debugDescription: String { return "debugDescription" }
}
Reflection.test("NSObject is properly CustomDebugStringConvertible") {
let object = StringConvertibleInDebugAndOtherwise()
expectEqual(String(reflecting: object), object.debugDescription)
}
Reflection.test("NSRange QuickLook") {
let rng = NSRange(location:Int.min, length:5)
let ql = PlaygroundQuickLook(reflecting: rng)
switch ql {
case .range(let loc, let len):
expectEqual(loc, Int64(Int.min))
expectEqual(len, 5)
default:
expectUnreachable("PlaygroundQuickLook for NSRange did not match Range")
}
}
class SomeSubclass : SomeClass {}
var ObjCConformsToProtocolTestSuite = TestSuite("ObjCConformsToProtocol")
ObjCConformsToProtocolTestSuite.test("cast/instance") {
expectTrue(SomeClass() is SomeObjCProto)
expectTrue(SomeSubclass() is SomeObjCProto)
}
ObjCConformsToProtocolTestSuite.test("cast/metatype") {
expectTrue(SomeClass.self is SomeObjCProto.Type)
expectTrue(SomeSubclass.self is SomeObjCProto.Type)
}
// SR-7357
extension Optional where Wrapped == NSData {
private class Inner {
}
var asInner: Inner {
return Inner()
}
}
var RuntimeClassNamesTestSuite = TestSuite("runtime class names")
RuntimeClassNamesTestSuite.test("private class nested in same-type-constrained extension") {
let base: NSData? = nil
let util = base.asInner
let clas = unsafeBitCast(type(of: util), to: NSObject.self)
// Name should look like _TtC1aP.*Inner
let desc = clas.description
expectEqual("_TtGC1a", desc.prefix(7))
expectEqual("Data_", desc.suffix(5))
}
runAllTests()
|
apache-2.0
|
e2285ad0bbc48c0667bb03d502fca85c
| 29.394018 | 149 | 0.71005 | 4.413331 | false | true | false | false |
Den-Ree/InstagramAPI
|
src/InstagramAPI/InstagramAPI/Example/ViewControllers/Comment/CommentTableViewController.swift
|
2
|
1564
|
//
// CommentTableViewController.swift
// InstagramAPI
//
// Created by Admin on 04.06.17.
// Copyright © 2017 ConceptOffice. All rights reserved.
//
import UIKit
class CommentTableViewController: UITableViewController {
var mediaId: String?
fileprivate var dataSource: [InstagramComment] = []
override func viewDidLoad() {
super.viewDidLoad()
let commentRouter = InstagramCommentRouter.getComments(mediaId: mediaId!)
InstagramClient().send(commentRouter, completion: {( comments: InstagramArrayResponse<InstagramComment>?, error: Error?) in
if error == nil {
if let data = comments?.data {
self.dataSource = data
self.tableView.reloadData()
}
}
})
}
}
extension CommentTableViewController {
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentCell
let comment = dataSource[indexPath.row]
cell.commentLabel.text = comment.text
cell.usernameLabel.text = comment.from.username
cell.dateLabel.text = comment.createdDate.description
return cell
}
}
|
mit
|
e09aef2a276efc0250c8b0d918d30fa4
| 29.647059 | 131 | 0.668586 | 5.025723 | false | false | false | false |
dreamsxin/swift
|
test/DebugInfo/argument.swift
|
6
|
2222
|
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | FileCheck %s
func markUsed<T>(_ t: T) {}
// CHECK-DAG: !DILocalVariable(name: "arg", arg: 1,{{.*}} line: [[@LINE+1]]
func a(_ arg : Int64)
{
// CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]]
var local = arg
}
// CHECK-DAG: !DILocalVariable(name: "a", arg: 1,{{.*}} line: [[@LINE+3]]
// CHECK-DAG: !DILocalVariable(name: "b", arg: 2,{{.*}} line: [[@LINE+2]]
// CHECK-DAG: !DILocalVariable(name: "c", arg: 3,{{.*}} line: [[@LINE+1]]
func many(_ a: Int64, b: (Int64, Int64), c: Int64) -> Int64 {
// CHECK-DAG: !DILocalVariable(name: "i1",{{.*}} line: [[@LINE+1]]
var i1 = a
// CHECK-DAG: !DILocalVariable(name: "i2",{{.*}} line: [[@LINE+2]]
// CHECK-DAG: !DILocalVariable(name: "i3",{{.*}} line: [[@LINE+1]]
var (i2, i3) : (Int64, Int64) = b
// CHECK-DAG: !DILocalVariable(name: "i4",{{.*}} line: [[@LINE+1]]
var i4 = c
return i1+i2+i3+i4
}
class A {
var member : Int64
// CHECK-DAG: !DILocalVariable(name: "a", arg: 1,{{.*}} line: [[@LINE+1]]
init(a: Int64) { member = a }
// CHECK-DAG: !DILocalVariable(name: "offset", arg: 1,{{.*}} line: [[@LINE+2]]
// CHECK-DAG: !DILocalVariable(name: "self", arg: 2,{{.*}} line: [[@LINE+1]]
func getValuePlus(_ offset: Int64) -> Int64 {
// CHECK-DAG: !DILocalVariable(name: "a",{{.*}} line: [[@LINE+1]]
var a = member
return a+offset
}
// CHECK-DAG: !DILocalVariable(name: "factor", arg: 1,{{.*}} line: [[@LINE+3]]
// CHECK-DAG: !DILocalVariable(name: "offset", arg: 2,{{.*}} line: [[@LINE+2]]
// CHECK-DAG: !DILocalVariable(name: "self", arg: 3,{{.*}} line: [[@LINE+1]]
func getValueTimesPlus(_ factor: Int64, offset: Int64) -> Int64 {
// CHECK-DAG: !DILocalVariable(name: "a",{{.*}} line: [[@LINE+1]]
var a = member
// CHECK-DAG: !DILocalVariable(name: "f",{{.*}} line: [[@LINE+1]]
var f = factor
return a*f+offset
}
// CHECK: !DILocalVariable(name: "self", arg: 1,{{.*}} line: [[@LINE+1]]
deinit {
markUsed(member)
}
}
// CHECK: !DILocalVariable(name: "x", arg: 1,{{.*}} line: [[@LINE+2]]
// CHECK: !DILocalVariable(name: "y", arg: 2,{{.*}} line: [[@LINE+1]]
func tuple(_ x: Int64, y: (Int64, Float, String)) -> Int64 {
return x+y.0
}
|
apache-2.0
|
dc9c96e793ceb7a92818e9d165123787
| 35.42623 | 79 | 0.569307 | 2.912189 | false | false | false | false |
loudnate/Loop
|
Loop/Views/PredictionInputEffectTableViewCell.swift
|
2
|
912
|
//
// PredictionInputEffectTableViewCell.swift
// Loop
//
// Created by Nate Racklyeft on 9/4/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
class PredictionInputEffectTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
override func layoutSubviews() {
super.layoutSubviews()
contentView.layoutMargins.left = separatorInset.left
contentView.layoutMargins.right = separatorInset.left
}
var enabled: Bool = true {
didSet {
if enabled {
titleLabel.textColor = UIColor.darkText
subtitleLabel.textColor = UIColor.darkText
} else {
titleLabel.textColor = UIColor.secondaryLabelColor
subtitleLabel.textColor = UIColor.secondaryLabelColor
}
}
}
}
|
apache-2.0
|
bdfe98f11321ebe7f4abe666c1f2350b
| 24.305556 | 69 | 0.644347 | 5.327485 | false | false | false | false |
youmyc/QRCodeScan
|
QRCodeScanSwiftDemo/QRCViewController.swift
|
1
|
2609
|
//
// QRCViewController.swift
// QRCodeScanSwiftDemo
//
// Created by youmy on 2018/11/29.
// Copyright © 2018 youmy. All rights reserved.
//
import UIKit
import ScanQRCode
protocol QRCViewControllerDelegate:NSObjectProtocol {
func didFinishedSacn(controller:QRCViewController, result:String)
}
class QRCViewController: UIViewController {
@IBOutlet weak var containerHconstraint: NSLayoutConstraint!
@IBOutlet weak var scanLineTopConstrint: NSLayoutConstraint!
@IBOutlet weak var desLb: UILabel!
@IBOutlet weak var borderView: BorderView!
var delegate:QRCViewControllerDelegate?
var scanView:ScanView?
var isBarCode:Bool = false
var qrcodeType:QRCodeType = QRCode
override func viewDidLoad() {
super.viewDidLoad()
scanView = ScanView(frame: UIScreen.main.bounds)
scanView?.delegate = self
view.insertSubview(scanView!, at: 0)
borderView.anglecolor = .red
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if isBarCode {
qrcodeType = BarCode
containerHconstraint.constant = (UIScreen.main.bounds.width - 83*2)/2.0
desLb.text = "将条形码放置在框内,即开始扫描"
}else{
qrcodeType = QRCode
containerHconstraint.constant = UIScreen.main.bounds.width - 83*2
desLb.text = "将二维码放置在框内,即开始扫描"
}
scan()
}
func scan(){
startAnimation()
scanView?.qrcode = qrcodeType
scanView?.startScan()
}
/// 冲击波动画
func startAnimation(){
scanLineTopConstrint.constant = -scanLineTopConstrint.constant
view.layoutIfNeeded()
UIView.animate(withDuration: 1.5) {
self.scanLineTopConstrint.constant = self.containerHconstraint.constant
UIView.setAnimationRepeatCount(MAXFLOAT)
self.view.layoutIfNeeded()
}
}
}
extension QRCViewController: ScanViewDelegate {
func lightSensorDidChange(_ scanView: ScanView, show flashLamp: Bool) {
}
func typeDidChange(_ scanView: ScanView, rect: CGRect) {
containerHconstraint.constant = rect.height
}
func didFinishScan(_ scanView: ScanView, result: String) {
scanView.delegate = nil
delegate?.didFinishedSacn(controller: self, result: result)
navigationController?.popViewController(animated: true)
}
}
|
mit
|
420f373272cfb4bc0ecdf40399d78206
| 24.897959 | 83 | 0.63554 | 4.581227 | false | false | false | false |
christiankm/FinanceKit
|
Sources/FinanceKit/Percentage.swift
|
1
|
1863
|
//
// FinanceKit
// Copyright © 2022 Christian Mitteldorf. All rights reserved.
// MIT license, see LICENSE file for details.
//
import Foundation
public struct Percentage: Equatable, Hashable, Codable {
/// Return a percentage of zero.
public static let zero = Percentage(decimal: 0)
// The percentage in decimal.
public let decimal: Double
/// Returns a formatted string with 2 decimal places, e.g. "12.37 %".
///
/// For more formatting options use `PercentageFormatter`.
public var formattedString: String? {
PercentageFormatter().string(from: self)
}
/// The percentage in basis points, corresponding to the percentage decimal times 1000.
public var basisPoints: Int {
Int(decimal * 1000)
}
/// Initialize with a decimal, e.g. 0.23 or 1.7.
public init(decimal: FloatLiteralType) {
self.decimal = decimal
}
/// Initialize with a decimal, e.g. 0.23 or 1.7.
public init(_ decimal: FloatLiteralType) {
self.decimal = decimal
}
/// Initialize with a percentage, e.g. 12% or 175%, without the symbol..
public init(percentage: FloatLiteralType) {
self.decimal = percentage / 100
}
/// Initialize with a percentage formatted as a string.
public init?(string: String) {
guard let percentage = PercentageFormatter().percentage(from: string) else {
return nil
}
self = percentage
}
}
// MARK: - Comparable
extension Percentage: Comparable {
public static func < (lhs: Percentage, rhs: Percentage) -> Bool {
lhs.decimal < rhs.decimal
}
}
// MARK: - Average
extension Collection where Element == Percentage {
/// Returns the average of all percentages in the collection.
public var average: Percentage {
Percentage(map(\.decimal).average)
}
}
|
mit
|
e3e5de0d7d55f64ff5b75d900482225a
| 25.6 | 91 | 0.648228 | 4.381176 | false | false | false | false |
objecthub/swift-lispkit
|
Sources/LispKit/Runtime/Evaluator.swift
|
1
|
9597
|
//
// Evaluator.swift
// LispKit
//
// Created by Matthias Zenger on 21/12/2021.
// Copyright © 2021-2022 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
///
/// Class `Evaluator` implements an API for
///
///
public final class Evaluator: TrackedObject {
/// Call tracing modes
public enum CallTracingMode {
case on
case off
case byProc
}
/// The context of this virtual machine
private unowned let context: Context
/// Procedures defined in low-level libraries
public internal(set) var raiseProc: Procedure? = nil
public internal(set) var raiseContinuableProc: Procedure? = nil
public internal(set) var loader: Procedure? = nil
public internal(set) var defineSpecial: SpecialForm? = nil
public internal(set) var defineValuesSpecial: SpecialForm? = nil
public private(set) var setParameterProc: Procedure!
public private(set) var currentDirectoryProc: Procedure!
/// Will be set to true if the `exit` function was invoked
public internal(set) var exitTriggered: Bool = false
/// When set to true, will print call and return traces
public var traceCalls: CallTracingMode = .off
/// Call stack cap
public var maxCallStack: Int = 20
/// The main virtual machine
private let main: VirtualMachine
/// The main evaluation thread object (it's just a proxy for the thread executing an expression)
private var mainThread: NativeThread! = nil
/// All managed threads
internal var threads = ThreadManager()
init(for context: Context, limitStack: Int = 10000000) {
self.context = context
self.main = VirtualMachine(for: context, limitStack: limitStack)
context.objects.manage(self.main)
super.init()
self.mainThread = NativeThread(EvalThread(worker: self))
self.setParameterProc = Procedure("_set-parameter", self.setParameter, nil)
self.currentDirectoryProc =
Procedure(.procedure(Procedure("_valid-current-path", self.validCurrentPath)),
.makeString(context.initialHomePath ??
context.fileHandler.currentDirectoryPath))
}
/// Returns the virtual machine owned by the active evaluation thread (or the main thread if
/// there is currently no active managed evaluation thread)
public var machine: VirtualMachine {
return self.threads.current?.value.machine ?? self.main
}
// Evaluation of code
/// Executes an evaluation function at the top-level, i.e. in the main virtual machine
public func execute(_ eval: (VirtualMachine) throws -> Expr) -> Expr {
self.mainThread.value.mutex.lock()
guard self.machine === self.main else {
self.mainThread.value.mutex.unlock()
preconditionFailure("executing source code not on main thread")
}
self.threads.register(thread: Thread.current, as: self.mainThread)
self.exitTriggered = false
self.mainThread.value.mutex.unlock()
var result = self.main.onTopLevelDo {
return try eval(self.main)
}
self.mainThread.value.mutex.lock()
if case .error(let err) = result, err.descriptor == .uncaught {
result = err.irritants[0]
}
self.mainThread.value.abandonLocks()
self.mainThread.value.mutex.unlock()
// Terminate all threads
self.threads.abortAll(except: Thread.current)
if !self.threads.waitForTerminationOfAll(timeout: 1.0) {
// Not sure why the following line is sometimes needed...
self.threads.abortAll(except: Thread.current)
_ = self.threads.waitForTerminationOfAll(timeout: 0.5)
}
self.threads.remove(thread: Thread.current)
return result
}
/// Aborts the currently running execution
public func abort() {
_ = self.mainThread.value.abort()
}
// Create evaluation threads
public func thread(for proc: Procedure, name: Expr? = nil, tag: Expr? = nil) -> NativeThread {
return NativeThread(EvalThread(parent: self.machine,
procedure: proc,
name: name ?? .false,
tag: tag ?? .false))
}
// Abortion of evaluation
/// Returns true if an abortion was requested.
public func isAbortionRequested() -> Bool {
return self.main.abortionRequested
}
// Parsing of expressions
/// Parses the given file and returns a list of parsed expressions.
public func parse(file path: String, foldCase: Bool = false) throws -> Expr {
let (sourceId, text) = try self.context.sources.readSource(for: path)
return try self.parse(str: text, sourceId: sourceId, foldCase: foldCase)
}
/// Parses the given string and returns a list of parsed expressions.
public func parse(str: String, sourceId: UInt16, foldCase: Bool = false) throws -> Expr {
return .makeList(try self.parseExprs(str: str, sourceId: sourceId, foldCase: foldCase))
}
/// Parses the given string and returns an array of parsed expressions.
public func parseExprs(file path: String, foldCase: Bool = false) throws -> Exprs {
let (sourceId, text) = try self.context.sources.readSource(for: path)
return try self.parseExprs(str: text,
sourceId: sourceId,
foldCase: foldCase)
}
/// Parses the given string and returns an array of parsed expressions.
public func parseExprs(str: String, sourceId: UInt16, foldCase: Bool = false) throws -> Exprs {
let input = TextInput(string: str,
abortionCallback: self.context.evaluator.isAbortionRequested)
let parser = Parser(symbols: self.context.symbols,
input: input,
sourceId: sourceId,
foldCase: foldCase)
var exprs = Exprs()
while !parser.finished {
exprs.append(try parser.parse().datum) // TODO: remove .datum
}
return exprs
}
// Parameter handling
private var parameters: HashTable {
return self.machine.parameters
}
public func getParam(_ param: Procedure) -> Expr? {
return self.getParameter(.procedure(param))
}
public func getParameter(_ param: Expr) -> Expr? {
guard case .some(.pair(_, .box(let cell))) = self.parameters.get(param) else {
guard case .procedure(let proc) = param,
case .parameter(let tuple) = proc.kind else {
return nil
}
return tuple.snd
}
return cell.value
}
public func setParam(_ param: Procedure, to value: Expr) -> Expr {
return self.setParameter(.procedure(param), to: value)
}
public func setParameter(_ param: Expr, to value: Expr) -> Expr {
guard case .some(.pair(_, .box(let cell))) = self.parameters.get(param) else {
guard case .procedure(let proc) = param,
case .parameter(let tuple) = proc.kind else {
preconditionFailure("cannot set parameter \(param)")
}
tuple.snd = value
return .void
}
cell.value = value
return .void
}
internal func bindParameter(_ param: Expr, to value: Expr) -> Expr {
self.parameters.add(key: param, mapsTo: .box(Cell(value)))
return .void
}
public var currentDirectoryPath: String {
get {
do {
return try self.getParam(self.currentDirectoryProc)!.asString()
} catch {
preconditionFailure("current directory path not a string")
}
}
set {
_ = self.setParam(self.currentDirectoryProc, to: .makeString(newValue))
}
}
private func validCurrentPath(param: Expr, expr: Expr, setter: Expr) throws -> Expr {
self.currentDirectoryPath =
self.context.fileHandler.path(try expr.asPath(), relativeTo: self.currentDirectoryPath)
return .makeString(self.currentDirectoryPath)
}
// Tracked object protocol
/// Mark evaluator
public override func mark(in gc: GarbageCollector) {
self.main.mark(in: gc)
self.mainThread.mark(in: gc)
self.threads.mark(in: gc)
if let proc = self.raiseProc {
gc.mark(proc)
}
if let proc = self.raiseContinuableProc {
gc.mark(proc)
}
}
/// Reset evaluator
public func release() {
self.threads.releaseAll()
self.main.clean()
self.mainThread = nil
self.raiseProc = nil
self.raiseContinuableProc = nil
self.loader = nil
self.defineSpecial = nil
self.defineValuesSpecial = nil
self.setParameterProc = nil
self.exitTriggered = false
self.traceCalls = .off
}
}
extension Evaluator: EvalThreadWorker {
public var evalMachine: VirtualMachine {
return self.main
}
public func start() {
// nothing to do here
}
public func stop() -> Thread? {
if self.main.executing {
self.main.requestAbortion()
self.context.delegate?.aborted()
}
return nil
}
public func guaranteeSecondary() throws {
throw RuntimeError.eval(.joinWithMainThread)
}
public func markDelegate(with gc: GarbageCollector) {
// nothing to do here
}
public func releaseDelegate() {
// nothing to do here
}
}
|
apache-2.0
|
ff73b8037fb0da8644386cee1f19cee2
| 31.418919 | 98 | 0.663401 | 4.194056 | false | false | false | false |
josherick/DailySpend
|
DailySpend/PeriodBrowserController.swift
|
1
|
3776
|
//
// PeriodBrowserController.swift
// DailySpend
//
// Created by Josh Sherick on 10/28/18.
// Copyright © 2018 Josh Sherick. All rights reserved.
//
import Foundation
class PeriodBrowserController {
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
let periodBrowserViewHeight: CGFloat = 40
var periodBrowser: PeriodBrowserView
init(delegate: PeriodSelectorViewDelegate, view: UIView) {
self.periodBrowser = PeriodBrowserView()
NotificationCenter.default.addObserver(
forName: .init("ChangedSpendIndicationColor"),
object: nil,
queue: nil,
using: updateBarTintColor
)
let periodBrowserFrame = CGRect(
x: 0,
y: 0,
width: view.frame.size.width,
height: periodBrowserViewHeight
)
periodBrowser = PeriodBrowserView(frame: periodBrowserFrame)
periodBrowser.delegate = delegate
periodBrowser.backgroundColor = appDelegate.spendIndicationColor
view.addSubview(periodBrowser)
}
/**
* Updates period browser with information based on selected goal and
* period.
*
* - Parameters:
* - goal: The goal to use to determine if buttons should be enabled,
* or `nil` if there is no selected goal.
* - recurringGoalPeriod: The period whose range should be displayed on
* the period browser, or `nil` if the goal is not a recurring goal.
*/
func updatePeriodBrowser(goal: Goal!, recurringGoalPeriod: CalendarPeriod?) {
if goal == nil {
periodBrowser.previousButtonEnabled = false
periodBrowser.nextButtonEnabled = false
periodBrowser.labelText = "None"
return
}
let df = DateFormatter()
df.dateFormat = "M/d/yy"
var start, end: String
periodBrowser.previousButtonEnabled = false
periodBrowser.nextButtonEnabled = false
if let period = recurringGoalPeriod {
// This is a recurring goal.
periodBrowser.previousButtonEnabled = true
periodBrowser.nextButtonEnabled = true
start = period.start.string(formatter: df)
let inclusiveDay = CalendarDay(dateInDay: period.end!).subtract(days: 1)
end = inclusiveDay.string(formatter: df, friendly: true)
// Check for no previous period.
if period.previousCalendarPeriod().start.gmtDate < goal.start!.gmtDate {
periodBrowser.previousButtonEnabled = false
}
// Check for no next period.
let nextPeriodDate = period.nextCalendarPeriod()
if nextPeriodDate == nil || nextPeriodDate!.start.gmtDate > CalendarDay().start.gmtDate {
periodBrowser.nextButtonEnabled = false
}
} else {
let interval = goal.periodInterval(for: goal.start!)!
start = interval.start.string(formatter: df)
if let intervalEnd = interval.end {
end = intervalEnd.string(formatter: df, friendly: true)
} else {
end = "Today"
}
}
periodBrowser.labelText = "\(start) - \(end)"
}
/**
* Updates the tint color of the navigation bar to the color specified
* by the app delegate.
*/
func updateBarTintColor(_: Notification) {
let newColor = self.appDelegate.spendIndicationColor
if self.periodBrowser.backgroundColor != newColor {
UIView.animate(withDuration: 0.2) {
self.periodBrowser.backgroundColor = newColor
}
}
}
}
|
mit
|
b606b0808e452b8cc76302f81f103471
| 33.953704 | 101 | 0.602914 | 4.980211 | false | false | false | false |
brentsimmons/Evergreen
|
Mac/MainWindow/AddFeed/AddTwitterFeedWindowController.swift
|
1
|
6015
|
//
// AddTwitterFeedWindowController.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/21/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import AppKit
import RSCore
import RSTree
import Articles
import Account
class AddTwitterFeedWindowController : NSWindowController, AddFeedWindowController {
@IBOutlet weak var typePopupButton: NSPopUpButton!
@IBOutlet weak var typeDescriptionLabel: NSTextField!
@IBOutlet weak var accountLabel: NSTextField!
@IBOutlet weak var accountPopupButton: NSPopUpButton!
@IBOutlet weak var screenSearchTextField: NSTextField!
@IBOutlet var nameTextField: NSTextField!
@IBOutlet var addButton: NSButton!
@IBOutlet var folderPopupButton: NSPopUpButton!
private weak var delegate: AddFeedWindowControllerDelegate?
private var folderTreeController: TreeController!
private var userEnteredScreenSearch: String? {
var s = screenSearchTextField.stringValue
s = s.collapsingWhitespace
if s.isEmpty {
return nil
}
return s
}
private var userEnteredTitle: String? {
var s = nameTextField.stringValue
s = s.collapsingWhitespace
if s.isEmpty {
return nil
}
return s
}
var hostWindow: NSWindow!
convenience init(folderTreeController: TreeController, delegate: AddFeedWindowControllerDelegate?) {
self.init(windowNibName: NSNib.Name("AddTwitterFeedSheet"))
self.folderTreeController = folderTreeController
self.delegate = delegate
}
func runSheetOnWindow(_ hostWindow: NSWindow) {
hostWindow.beginSheet(window!) { (returnCode: NSApplication.ModalResponse) -> Void in
}
}
override func windowDidLoad() {
let accountMenu = NSMenu()
for feedProvider in ExtensionPointManager.shared.activeFeedProviders {
if let twitterFeedProvider = feedProvider as? TwitterFeedProvider {
let accountMenuItem = NSMenuItem()
accountMenuItem.title = "@\(twitterFeedProvider.screenName)"
accountMenu.addItem(accountMenuItem)
}
}
accountPopupButton.menu = accountMenu
folderPopupButton.menu = FolderTreeMenu.createFolderPopupMenu(with: folderTreeController.rootNode, restrictToSpecialAccounts: true)
if let container = AddWebFeedDefaultContainer.defaultContainer {
if let folder = container as? Folder, let account = folder.account {
FolderTreeMenu.select(account: account, folder: folder, in: folderPopupButton)
} else {
if let account = container as? Account {
FolderTreeMenu.select(account: account, folder: nil, in: folderPopupButton)
}
}
}
updateUI()
}
// MARK: Actions
@IBAction func selectedType(_ sender: Any) {
screenSearchTextField.stringValue = ""
updateUI()
}
@IBAction func cancel(_ sender: Any?) {
cancelSheet()
}
@IBAction func addFeed(_ sender: Any?) {
guard let type = TwitterFeedType(rawValue: typePopupButton.selectedItem?.tag ?? 0),
let atUsername = accountPopupButton.selectedItem?.title else { return }
let username = String(atUsername[atUsername.index(atUsername.startIndex, offsetBy: 1)..<atUsername.endIndex])
var screenSearch = userEnteredScreenSearch
if let screenName = screenSearch, type == .screenName && screenName.starts(with: "@") {
screenSearch = String(screenName[screenName.index(screenName.startIndex, offsetBy: 1)..<screenName.endIndex])
}
guard let url = TwitterFeedProvider.buildURL(type, username: username, screenName: screenSearch, searchField: screenSearch) else { return }
let container = selectedContainer()!
AddWebFeedDefaultContainer.saveDefaultContainer(container)
delegate?.addFeedWindowController(self, userEnteredURL: url, userEnteredTitle: userEnteredTitle, container: container)
}
}
extension AddTwitterFeedWindowController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
updateUI()
}
}
private extension AddTwitterFeedWindowController {
private func updateUI() {
switch typePopupButton.selectedItem?.tag ?? 0 {
case 0:
accountLabel.isHidden = false
accountPopupButton.isHidden = false
typeDescriptionLabel.stringValue = NSLocalizedString("Tweets from everyone you follow", comment: "Home Timeline")
screenSearchTextField.isHidden = true
addButton.isEnabled = true
case 1:
accountLabel.isHidden = false
accountPopupButton.isHidden = false
typeDescriptionLabel.stringValue = NSLocalizedString("Tweets mentioning you", comment: "Mentions")
screenSearchTextField.isHidden = true
addButton.isEnabled = true
case 2:
accountLabel.isHidden = true
accountPopupButton.isHidden = true
var screenSearch = userEnteredScreenSearch
if screenSearch != nil {
if let screenName = screenSearch, screenName.starts(with: "@") {
screenSearch = String(screenName[screenName.index(screenName.startIndex, offsetBy: 1)..<screenName.endIndex])
}
typeDescriptionLabel.stringValue = NSLocalizedString("Tweets from @\(screenSearch!)", comment: "Home Timeline")
} else {
typeDescriptionLabel.stringValue = ""
}
screenSearchTextField.placeholderString = NSLocalizedString("@name", comment: "@name")
screenSearchTextField.isHidden = false
addButton.isEnabled = !screenSearchTextField.stringValue.isEmpty
default:
accountLabel.isHidden = true
accountPopupButton.isHidden = true
if !screenSearchTextField.stringValue.isEmpty {
typeDescriptionLabel.stringValue = NSLocalizedString("Tweets that contain \(screenSearchTextField.stringValue)", comment: "Home Timeline")
} else {
typeDescriptionLabel.stringValue = ""
}
screenSearchTextField.placeholderString = NSLocalizedString("Search Term or #hashtag", comment: "Search Term")
screenSearchTextField.isHidden = false
addButton.isEnabled = !screenSearchTextField.stringValue.isEmpty
}
}
func cancelSheet() {
delegate?.addFeedWindowControllerUserDidCancel(self)
}
func selectedContainer() -> Container? {
return folderPopupButton.selectedItem?.representedObject as? Container
}
}
|
mit
|
5d4b0942a3ec3ef928eeb2c759cc3533
| 30 | 142 | 0.753908 | 4.286529 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/Moya/Sources/RxMoya/Single+Response.swift
|
2
|
2488
|
import Foundation
import RxSwift
#if !COCOAPODS
import Moya
#endif
#if canImport(UIKit)
import UIKit.UIImage
#elseif canImport(AppKit)
import AppKit.NSImage
#endif
/// Extension for processing raw NSData generated by network access.
extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
/// Filters out responses that don't fall within the given closed range, generating errors when others are encountered.
public func filter<R: RangeExpression>(statusCodes: R) -> Single<ElementType> where R.Bound == Int {
return flatMap { .just(try $0.filter(statusCodes: statusCodes)) }
}
/// Filters out responses that have the specified `statusCode`.
public func filter(statusCode: Int) -> Single<ElementType> {
return flatMap { .just(try $0.filter(statusCode: statusCode)) }
}
/// Filters out responses where `statusCode` falls within the range 200 - 299.
public func filterSuccessfulStatusCodes() -> Single<ElementType> {
return flatMap { .just(try $0.filterSuccessfulStatusCodes()) }
}
/// Filters out responses where `statusCode` falls within the range 200 - 399
public func filterSuccessfulStatusAndRedirectCodes() -> Single<ElementType> {
return flatMap { .just(try $0.filterSuccessfulStatusAndRedirectCodes()) }
}
/// Maps data received from the signal into an Image. If the conversion fails, the signal errors.
public func mapImage() -> Single<Image> {
return flatMap { .just(try $0.mapImage()) }
}
/// Maps data received from the signal into a JSON object. If the conversion fails, the signal errors.
public func mapJSON(failsOnEmptyData: Bool = true) -> Single<Any> {
return flatMap { .just(try $0.mapJSON(failsOnEmptyData: failsOnEmptyData)) }
}
/// Maps received data at key path into a String. If the conversion fails, the signal errors.
public func mapString(atKeyPath keyPath: String? = nil) -> Single<String> {
return flatMap { .just(try $0.mapString(atKeyPath: keyPath)) }
}
/// Maps received data at key path into a Decodable object. If the conversion fails, the signal errors.
public func map<D: Decodable>(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) -> Single<D> {
return flatMap { .just(try $0.map(type, atKeyPath: keyPath, using: decoder, failsOnEmptyData: failsOnEmptyData)) }
}
}
|
apache-2.0
|
9f64afdb61770a96cc4a4afe78c63709
| 44.236364 | 173 | 0.703376 | 4.573529 | false | false | false | false |
kylef/JSONSchema.swift
|
Sources/Applicators/patternProperties.swift
|
1
|
1361
|
import Foundation
func patternProperties(context: Context, patternProperties: Any, instance: Any, schema: [String: Any]) throws -> AnySequence<ValidationError> {
guard let instance = instance as? [String: Any] else {
return AnySequence(EmptyCollection())
}
guard let patternProperties = patternProperties as? [String: Any] else {
return AnySequence(EmptyCollection())
}
var results: [AnySequence<ValidationError>] = []
for (pattern, schema) in patternProperties {
do {
let expression = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0))
let keys = instance.keys.filter {
(key: String) in expression.matches(in: key, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, key.count)).count > 0
}
for key in keys {
context.instanceLocation.push(key)
defer { context.instanceLocation.pop() }
results.append(try context.descend(instance: instance[key]!, subschema: schema))
}
} catch {
return AnySequence([
ValidationError(
"[Schema] '\(pattern)' is not a valid regex pattern for patternProperties",
instanceLocation: context.instanceLocation,
keywordLocation: context.keywordLocation
),
])
}
}
return AnySequence(results.joined())
}
|
bsd-3-clause
|
45e3d6038adb124eac72213a15a9ba07
| 33.897436 | 155 | 0.681852 | 4.629252 | false | false | false | false |
iOSWizards/AwesomeMedia
|
AwesomeMedia/Classes/Controllers/AwesomeMediaVerticalVideoViewController.swift
|
1
|
12148
|
//
// AwesomeMediaAudioSoulvanaViewController.swift
// AwesomeMedia
//
// Created by Evandro Harrison Hoffmann on 8/8/18.
//
import UIKit
import AVKit
public class AwesomeMediaVerticalVideoViewController: UIViewController {
@IBOutlet public weak var mediaView: UIView!
@IBOutlet public weak var authorImageView: UIImageView!
@IBOutlet public weak var authorNameLabel: UILabel!
@IBOutlet public weak var aboutAudioTextView: UITextView!
@IBOutlet public weak var coverImageView: UIImageView!
@IBOutlet public weak var minimizeButton: UIButton!
@IBOutlet public weak var toggleControlsButton: UIButton!
@IBOutlet public weak var shareButton: UIButton!
@IBOutlet public weak var controlView: AwesomeMediaAudioControlView!
// Public Variaables
public var mediaParams = AwesomeMediaParams()
// Private Variables
fileprivate var backgroundPlayer = AVPlayer()
fileprivate var backgroundPlayerLayer = AwesomeMediaPlayerLayer.newInstance
public override func viewDidLoad() {
super.viewDidLoad()
// configure controller
configure()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Add observers
addObservers()
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Remove observers
removeObservers()
}
/*public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// track event
track(event: .changedOrientation, source: .audioFullscreen, value: UIApplication.shared.statusBarOrientation)
}*/
public override var shouldAutorotate: Bool {
return false
}
public override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
// Configure
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
backgroundPlayerLayer.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
}
fileprivate func configure() {
configureControls()
loadCoverImage()
setupAuthorInfo()
play()
// add background video
//configureBackgroundVideo()
// Refresh controls
refreshControls()
// check for loading state
authorImageView.stopLoadingAnimation()
if AwesomeMediaManager.shared.mediaIsLoading(withParams: mediaParams) {
authorImageView.startLoadingAnimation()
}
// check for media playing
if let item = sharedAVPlayer.currentItem(withParams: mediaParams) {
controlView?.update(withItem: item)
backgroundPlayer.play()
} else {
sharedAVPlayer.pause()
}
}
fileprivate func setupAuthorInfo() {
authorImageView.setImage(mediaParams.coverUrl)
authorNameLabel.text = mediaParams.author
aboutAudioTextView.text = mediaParams.about
}
public override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
fileprivate func configureControls() {
controlView.configure(withParams: mediaParams, trackingSource: .audioFullscreen)
// show or hide sharing and favourite buttons
configureSharingAndFavourite()
// play/pause
controlView.playCallback = { [weak self] (isPlaying) in
if isPlaying {
self?.play()
//self.controlView.setupAutoHide()
} else {
sharedAVPlayer.pause()
}
}
// seek slider
controlView.timeSliderChangedCallback = { (time) in
sharedAVPlayer.seek(toTime: time)
}
controlView.timeSliderFinishedDraggingCallback = { (play) in
if play {
sharedAVPlayer.play()
}
}
// Rewind
controlView.rewindCallback = {
sharedAVPlayer.seekBackward()
}
// Forward
controlView.forwardCallback = {
sharedAVPlayer.seekForward()
}
// Favourite
controlView.favouriteCallback = { [weak self] (isFavourited) in
guard let self = self else { return }
if isFavourited {
notifyMediaEvent(.favourited, object: self.mediaParams as AnyObject)
} else {
notifyMediaEvent(.unfavourited, object: self.mediaParams as AnyObject)
}
}
}
fileprivate func configureBackgroundVideo() {
guard let backgroundStringUrl = mediaParams.backgroundUrl, let backgroundUrl = URL(string: backgroundStringUrl) else {
return
}
// configure player item
let playerItem = AVPlayerItem(url: backgroundUrl)
backgroundPlayer.replaceCurrentItem(with: playerItem)
backgroundPlayer.isMuted = true
// configures autoplay loop
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: playerItem, queue: .main) { _ in
self.backgroundPlayer.seek(to: CMTime.zero)
self.backgroundPlayer.play()
}
// add player layer
backgroundPlayerLayer.player = backgroundPlayer
backgroundPlayerLayer.backgroundColor = nil
mediaView.addPlayerLayer(backgroundPlayerLayer)
}
// MARK: - Events
@IBAction func minimizeButtonPressed(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
// track event
track(event: .toggleFullscreen, source: .audioFullscreen)
}
@IBAction func toggleControls(_ sender: Any) {
controlView.show()
}
@IBAction func shareButtonPressed(_ sender: Any) {
guard let sharingItems = self.mediaParams.sharingItems else {
return
}
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
fileprivate func play() {
AwesomeMediaManager.shared.playMedia(
withParams: self.mediaParams,
inPlayerLayer: AwesomeMediaPlayerLayer.shared,
viewController: self)
}
fileprivate func refreshControls() {
// update slider
timeUpdated()
// update play button state
controlView.playButton.isSelected = sharedAVPlayer.isPlaying(withParams: mediaParams)
}
fileprivate func configureSharingAndFavourite() {
// show or hide shareButton
showButton( mediaParams.sharingItems != nil, button: shareButton)
// show or hide favouriteButton
showButton(mediaParams.favourited != nil, button: controlView.favouriteButton)
if let favourited = mediaParams.favourited {
controlView.favouriteButton?.isSelected = favourited
}
}
fileprivate func showButton(_ show: Bool, button: UIButton?) {
button?.isUserInteractionEnabled = show
button?.alpha = show ? 1.0 : 0
}
}
// MARK: - Media Information
extension AwesomeMediaVerticalVideoViewController {
public func loadCoverImage() {
guard let coverImageUrl = mediaParams.coverUrl else {
return
}
// set the cover image
coverImageView.setImage(coverImageUrl)
}
}
// MARK: - Observers
extension AwesomeMediaVerticalVideoViewController: AwesomeMediaEventObserver {
public func addObservers() {
AwesomeMediaNotificationCenter.addObservers([.basic, .timeUpdated, .speedRateChanged, .timedOut, .stopped], to: self)
}
public func removeObservers() {
AwesomeMediaNotificationCenter.removeObservers(from: self)
}
public func startedPlaying() {
guard sharedAVPlayer.isPlaying(withParams: mediaParams) else {
return
}
controlView.playButton.isSelected = true
// update Control Center
AwesomeMediaControlCenter.updateControlCenter(withParams: mediaParams)
// remove media alert if present
removeAlertIfPresent()
// play background
backgroundPlayer.play()
}
public func pausedPlaying() {
controlView.playButton.isSelected = sharedAVPlayer.isPlaying(withParams: mediaParams)
// cancels auto hide
controlView.show()
// pause background
backgroundPlayer.pause()
}
public func stoppedPlaying() {
pausedPlaying()
stoppedBuffering()
finishedPlaying()
// remove media alert if present
removeAlertIfPresent()
// cancels auto hide
controlView.show()
// pause background
backgroundPlayer.pause()
}
public func startedBuffering() {
guard sharedAVPlayer.isCurrentItem(withParams: mediaParams) else {
stoppedBuffering()
return
}
authorImageView.startLoadingAnimation()
controlView.lock(true, animated: true)
configureSharingAndFavourite()
// cancels auto hide
controlView.show()
// pauses background
backgroundPlayer.pause()
}
public func stoppedBuffering() {
authorImageView.stopLoadingAnimation()
controlView.lock(false, animated: true)
configureSharingAndFavourite()
// remove media alert if present
removeAlertIfPresent()
// setup auto hide
//controlView?.setupAutoHide()
// play background
backgroundPlayer.play()
}
public func finishedPlaying() {
controlView.playButton.isSelected = false
controlView.lock(false, animated: true)
configureSharingAndFavourite()
// pause background
backgroundPlayer.pause()
// close Player
dismiss(animated: true, completion: nil)
}
public func timedOut() {
showMediaTimedOutAlert()
}
public func speedRateChanged() {
controlView.speedLabel?.text = AwesomeMediaSpeed.speedLabelForCurrentSpeed
}
public func timeUpdated() {
guard let item = sharedAVPlayer.currentItem(withParams: mediaParams) else {
return
}
//AwesomeMedia.log("Current time updated: \(item.currentTime().seconds) of \(CMTimeGetSeconds(item.duration))")
// update time controls
controlView?.update(withItem: item)
}
}
// MARK: - ViewController Initialization
extension AwesomeMediaVerticalVideoViewController {
public static var newInstance: AwesomeMediaVerticalVideoViewController {
let storyboard = UIStoryboard(name: "AwesomeMedia", bundle: AwesomeMedia.bundle)
return storyboard.instantiateViewController(withIdentifier: "AwesomeMediaVerticalVideoViewController") as! AwesomeMediaVerticalVideoViewController
}
}
extension UIViewController {
public func presentVerticalVideoFullscreen(withMediaParams mediaParams: AwesomeMediaParams) {
AwesomeMediaPlayerType.type = .verticalVideo
let viewController = AwesomeMediaVerticalVideoViewController.newInstance
viewController.mediaParams = mediaParams
interactor = AwesomeMediaInteractor()
viewController.modalPresentationStyle = .fullScreen
viewController.transitioningDelegate = self
viewController.interactor = interactor
self.present(viewController, animated: true, completion: nil)
}
}
|
mit
|
07a1d2df49abe5e88f86eb3da7e69a34
| 29.676768 | 154 | 0.63138 | 5.934538 | false | false | false | false |
u10int/Kinetic
|
Example/Kinetic/PhysicsViewController.swift
|
1
|
4767
|
//
// PhysicsViewController.swift
// Kinetic
//
// Created by Nicholas Shipes on 1/22/16.
// Copyright © 2016 Urban10 Interactive, LLC. All rights reserved.
//
import UIKit
import Kinetic
class PhysicsViewController: ExampleViewController {
var square: UIView!
var tensionSlider: UISlider!
var frictionSlider: UISlider!
var tensionValue: UILabel!
var frictionValue: UILabel!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
title = "Physics Tween"
showsControls = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
hideSliderControls()
square = UIView()
square.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
square.backgroundColor = UIColor(red: 0.4693, green: 0.0, blue: 1.0, alpha: 1.0)
view.addSubview(square)
let tensionLabel = UILabel()
tensionLabel.translatesAutoresizingMaskIntoConstraints = false
tensionLabel.font = UIFont.systemFont(ofSize: 16)
tensionLabel.textColor = UIColor(white: 0.1, alpha: 1)
tensionLabel.text = "Tension"
view.addSubview(tensionLabel)
tensionValue = UILabel()
tensionValue.translatesAutoresizingMaskIntoConstraints = false
tensionValue.font = UIFont.boldSystemFont(ofSize: 16)
tensionValue.textColor = UIColor(white: 0.1, alpha: 1)
tensionValue.text = "0"
view.addSubview(tensionValue)
tensionSlider = UISlider()
tensionSlider.translatesAutoresizingMaskIntoConstraints = false
tensionSlider.minimumValue = 0
tensionSlider.maximumValue = 300
tensionSlider.addTarget(self, action: #selector(PhysicsViewController.tensionChanged(_:)), for: .valueChanged)
view.addSubview(tensionSlider)
let frictionLabel = UILabel()
frictionLabel.translatesAutoresizingMaskIntoConstraints = false
frictionLabel.font = UIFont.systemFont(ofSize: 16)
frictionLabel.textColor = UIColor(white: 0.1, alpha: 1)
frictionLabel.text = "Friction"
view.addSubview(frictionLabel)
frictionValue = UILabel()
frictionValue.translatesAutoresizingMaskIntoConstraints = false
frictionValue.font = UIFont.boldSystemFont(ofSize: 16)
frictionValue.textColor = UIColor(white: 0.1, alpha: 1)
frictionValue.text = "0"
view.addSubview(frictionValue)
frictionSlider = UISlider()
frictionSlider.translatesAutoresizingMaskIntoConstraints = false
frictionSlider.minimumValue = 0
frictionSlider.maximumValue = 50
frictionSlider.addTarget(self, action: #selector(PhysicsViewController.frictionChanged(_:)), for: .valueChanged)
view.addSubview(frictionSlider)
// layout
let views = ["play": playButton, "tension": tensionSlider, "tensionLabel": tensionLabel, "tensionValue": tensionValue, "friction": frictionSlider, "frictionLabel": frictionLabel, "frictionValue": frictionValue] as [String : Any]
let tensionHorizontal = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[tensionLabel(80)]-10-[tension]-10-[tensionValue(40)]-20-|", options: .alignAllCenterY, metrics: nil, views: views)
let tensionLabelY = NSLayoutConstraint(item: tensionLabel, attribute: .bottom, relatedBy: .equal, toItem: playButton, attribute: .top, multiplier: 1, constant: -50)
let frictionHorizontal = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[frictionLabel(80)]-10-[friction]-10-[frictionValue(40)]-20-|", options: .alignAllCenterY, metrics: nil, views: views)
let frictionLabelY = NSLayoutConstraint(item: frictionLabel, attribute: .bottom, relatedBy: .equal, toItem: tensionLabel, attribute: .top, multiplier: 1, constant: -30)
view.addConstraints(tensionHorizontal)
view.addConstraint(tensionLabelY)
view.addConstraints(frictionHorizontal)
view.addConstraint(frictionLabelY)
tensionSlider.setValue(70, animated: false)
tensionValue.text = "\(Int(round(tensionSlider.value)))"
frictionSlider.setValue(10, animated: false)
frictionValue.text = "\(Int(round(frictionSlider.value)))"
let tween = Kinetic.animate(square)
.to(X(250), Size(height: 100))
.duration(0.5)
animation = tween
animation?.on(.completed) { (animation) in
print("tween complete")
}
}
override func play() {
if let tween = animation as? Tween {
tween.spring(tension: Double(tensionSlider.value), friction: Double(frictionSlider.value))
}
animation?.play()
}
override func reset() {
super.reset()
Kinetic.killTweensOf(square)
}
func tensionChanged(_ sender: UISlider) {
tensionValue.text = "\(Int(round(sender.value)))"
reset()
}
func frictionChanged(_ sender: UISlider) {
frictionValue.text = "\(Int(round(sender.value)))"
reset()
}
}
|
mit
|
c764328846545901441f6a1b5b15b798
| 34.834586 | 230 | 0.747587 | 3.85287 | false | false | false | false |
kent426/CoreDataTableView-iOS
|
CoreDataTableView/models/Category.swift
|
1
|
2241
|
//
// Category.swift
// CoreDataTableView
//
// Created by kenth on 2017-10-26.
// Copyright © 2017 kenth. All rights reserved.
//
import Foundation
import CoreData
//this is the coredata object class
class Category: NSManagedObject {
//create func
class func CreateCategory(CategoryName: String, in context: NSManagedObjectContext) -> Category?
{
//query to check if the db had the name already
//if so, return nil
let fetchRequest: NSFetchRequest<Category> = Category.fetchRequest()
fetchRequest.predicate = NSPredicate.init(format: "categoryName = %@", argumentArray: [CategoryName])
let object = try! context.fetch(fetchRequest)
if(object.count >= 1) {
print("duplicate")
return nil
}
//1: to get a new object(new row in db)
let newCategory = Category(context: context)
//2:set the attributes
newCategory.categoryName = CategoryName
newCategory.creationDate = Date()
return newCategory
//3: after call context.save();
}
//update date
class func UpdateDate(CategoryName: String,context: NSManagedObjectContext) {
let fetchRequest: NSFetchRequest<Category> = Category.fetchRequest()
fetchRequest.predicate = NSPredicate.init(format: "categoryName = %@", argumentArray: [CategoryName])
let object = try! context.fetch(fetchRequest)[0]
object.setValue(Date(), forKey: "creationDate")
do {
try context.save()
} catch {
print(error)
fatalError("fail to update.")
}
}
//delete
class func Delete(CategoryName: String,context: NSManagedObjectContext) {
let fetchRequest: NSFetchRequest<Category> = Category.fetchRequest()
fetchRequest.predicate = NSPredicate.init(format: "categoryName = %@", argumentArray: [CategoryName])
let object = try! context.fetch(fetchRequest)
context.delete(object[0])
do {
try context.save()
} catch {
print(error)
fatalError("fail to delete.")
}
}
}
|
mit
|
7f672bac071cdc78e5448fcd14a23709
| 28.090909 | 109 | 0.604018 | 5 | false | false | false | false |
breadwallet/breadwallet-ios
|
breadwallet/src/Views/TransactionCells/TxMemoCell.swift
|
1
|
3636
|
//
// TxMemoCell.swift
// breadwallet
//
// Created by Ehsan Rezaie on 2018-01-02.
// Copyright © 2018-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class TxMemoCell: TxDetailRowCell {
// MARK: - Views
fileprivate let textView = UITextView()
fileprivate let placeholderLabel = UILabel(font: .customBody(size: 14.0), color: .lightGray)
// MARK: - Vars
private var viewModel: TxDetailViewModel!
private weak var tableView: UITableView!
// MARK: - Init
override func addSubviews() {
super.addSubviews()
container.addSubview(textView)
textView.addSubview(placeholderLabel)
}
override func addConstraints() {
super.addConstraints()
textView.constrain([
textView.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: C.padding[2]),
textView.trailingAnchor.constraint(equalTo: container.trailingAnchor),
textView.topAnchor.constraint(equalTo: container.topAnchor),
textView.bottomAnchor.constraint(equalTo: container.bottomAnchor)
])
placeholderLabel.constrain([
placeholderLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor),
placeholderLabel.topAnchor.constraint(equalTo: container.topAnchor),
placeholderLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor),
placeholderLabel.widthAnchor.constraint(equalTo: textView.widthAnchor)
])
placeholderLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
}
override func setupStyle() {
super.setupStyle()
textView.font = .customBody(size: 14.0)
textView.textColor = .darkGray
textView.textAlignment = .right
textView.isScrollEnabled = false
textView.returnKeyType = .done
textView.delegate = self
placeholderLabel.textAlignment = .right
placeholderLabel.text = S.TransactionDetails.commentsPlaceholder
}
// MARK: -
func set(viewModel: TxDetailViewModel, tableView: UITableView) {
self.tableView = tableView
self.viewModel = viewModel
textView.text = viewModel.comment
placeholderLabel.isHidden = !textView.text.isEmpty
if viewModel.gift != nil {
textView.isEditable = false
textView.isSelectable = false
}
}
fileprivate func saveComment(comment: String) {
guard let kvStore = Backend.kvStore else { return }
viewModel.tx.save(comment: comment, kvStore: kvStore)
Store.trigger(name: .txMetaDataUpdated(viewModel.tx.hash))
}
}
extension TxMemoCell: UITextViewDelegate {
func textViewDidEndEditing(_ textView: UITextView) {
guard let text = textView.text else { return }
saveComment(comment: text)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
textView.resignFirstResponder()
return false
}
let count = (textView.text ?? "").utf8.count + text.utf8.count
if count > C.maxMemoLength {
return false
} else {
return true
}
}
func textViewDidChange(_ textView: UITextView) {
placeholderLabel.isHidden = !textView.text.isEmpty
// trigger cell resize
tableView.beginUpdates()
tableView.endUpdates()
}
}
|
mit
|
e46005518161ff12ec1af080eb606198
| 32.045455 | 116 | 0.647043 | 5.222701 | false | false | false | false |
wangweicheng7/ClouldFisher
|
Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypes.swift
|
2
|
9004
|
//
// BasicTypes.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-02-17.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import ObjectMapper
class BasicTypes: Mappable {
var bool: Bool = true
var boolOptional: Bool?
var boolImplicityUnwrapped: Bool!
var int: Int = 0
var intOptional: Int?
var intImplicityUnwrapped: Int!
var double: Double = 1.1
var doubleOptional: Double?
var doubleImplicityUnwrapped: Double!
var float: Float = 1.11
var floatOptional: Float?
var floatImplicityUnwrapped: Float!
var string: String = ""
var stringOptional: String?
var stringImplicityUnwrapped: String!
var anyObject: Any = true
var anyObjectOptional: Any?
var anyObjectImplicitlyUnwrapped: Any!
var arrayBool: Array<Bool> = []
var arrayBoolOptional: Array<Bool>?
var arrayBoolImplicityUnwrapped: Array<Bool>!
var arrayInt: Array<Int> = []
var arrayIntOptional: Array<Int>?
var arrayIntImplicityUnwrapped: Array<Int>!
var arrayDouble: Array<Double> = []
var arrayDoubleOptional: Array<Double>?
var arrayDoubleImplicityUnwrapped: Array<Double>!
var arrayFloat: Array<Float> = []
var arrayFloatOptional: Array<Float>?
var arrayFloatImplicityUnwrapped: Array<Float>!
var arrayString: Array<String> = []
var arrayStringOptional: Array<String>?
var arrayStringImplicityUnwrapped: Array<String>!
var arrayAnyObject: Array<Any> = []
var arrayAnyObjectOptional: Array<Any>?
var arrayAnyObjectImplicitlyUnwrapped: Array<Any>!
var dictBool: Dictionary<String,Bool> = [:]
var dictBoolOptional: Dictionary<String, Bool>?
var dictBoolImplicityUnwrapped: Dictionary<String, Bool>!
var dictInt: Dictionary<String,Int> = [:]
var dictIntOptional: Dictionary<String,Int>?
var dictIntImplicityUnwrapped: Dictionary<String,Int>!
var dictDouble: Dictionary<String,Double> = [:]
var dictDoubleOptional: Dictionary<String,Double>?
var dictDoubleImplicityUnwrapped: Dictionary<String,Double>!
var dictFloat: Dictionary<String,Float> = [:]
var dictFloatOptional: Dictionary<String,Float>?
var dictFloatImplicityUnwrapped: Dictionary<String,Float>!
var dictString: Dictionary<String,String> = [:]
var dictStringOptional: Dictionary<String,String>?
var dictStringImplicityUnwrapped: Dictionary<String,String>!
var dictAnyObject: Dictionary<String, Any> = [:]
var dictAnyObjectOptional: Dictionary<String, Any>?
var dictAnyObjectImplicitlyUnwrapped: Dictionary<String, Any>!
enum EnumInt: Int {
case Default
case Another
}
var enumInt: EnumInt = .Default
var enumIntOptional: EnumInt?
var enumIntImplicitlyUnwrapped: EnumInt!
enum EnumDouble: Double {
case Default
case Another
}
var enumDouble: EnumDouble = .Default
var enumDoubleOptional: EnumDouble?
var enumDoubleImplicitlyUnwrapped: EnumDouble!
enum EnumFloat: Float {
case Default
case Another
}
var enumFloat: EnumFloat = .Default
var enumFloatOptional: EnumFloat?
var enumFloatImplicitlyUnwrapped: EnumFloat!
enum EnumString: String {
case Default = "Default"
case Another = "Another"
}
var enumString: EnumString = .Default
var enumStringOptional: EnumString?
var enumStringImplicitlyUnwrapped: EnumString!
var arrayEnumInt: [EnumInt] = []
var arrayEnumIntOptional: [EnumInt]?
var arrayEnumIntImplicitlyUnwrapped: [EnumInt]!
var dictEnumInt: [String: EnumInt] = [:]
var dictEnumIntOptional: [String: EnumInt]?
var dictEnumIntImplicitlyUnwrapped: [String: EnumInt]!
init(){
}
required init?(map: Map){
}
func mapping(map: Map) {
bool <- map["bool"]
boolOptional <- map["boolOpt"]
boolImplicityUnwrapped <- map["boolImp"]
int <- map["int"]
intOptional <- map["intOpt"]
intImplicityUnwrapped <- map["intImp"]
double <- map["double"]
doubleOptional <- map["doubleOpt"]
doubleImplicityUnwrapped <- map["doubleImp"]
float <- map["float"]
floatOptional <- map["floatOpt"]
floatImplicityUnwrapped <- map["floatImp"]
string <- map["string"]
stringOptional <- map["stringOpt"]
stringImplicityUnwrapped <- map["stringImp"]
anyObject <- map["anyObject"]
anyObjectOptional <- map["anyObjectOpt"]
anyObjectImplicitlyUnwrapped <- map["anyObjectImp"]
arrayBool <- map["arrayBool"]
arrayBoolOptional <- map["arrayBoolOpt"]
arrayBoolImplicityUnwrapped <- map["arrayBoolImp"]
arrayInt <- map["arrayInt"]
arrayIntOptional <- map["arrayIntOpt"]
arrayIntImplicityUnwrapped <- map["arrayIntImp"]
arrayDouble <- map["arrayDouble"]
arrayDoubleOptional <- map["arrayDoubleOpt"]
arrayDoubleImplicityUnwrapped <- map["arrayDoubleImp"]
arrayFloat <- map["arrayFloat"]
arrayFloatOptional <- map["arrayFloatOpt"]
arrayFloatImplicityUnwrapped <- map["arrayFloatImp"]
arrayString <- map["arrayString"]
arrayStringOptional <- map["arrayStringOpt"]
arrayStringImplicityUnwrapped <- map["arrayStringImp"]
arrayAnyObject <- map["arrayAnyObject"]
arrayAnyObjectOptional <- map["arrayAnyObjectOpt"]
arrayAnyObjectImplicitlyUnwrapped <- map["arrayAnyObjectImp"]
dictBool <- map["dictBool"]
dictBoolOptional <- map["dictBoolOpt"]
dictBoolImplicityUnwrapped <- map["dictBoolImp"]
dictInt <- map["dictInt"]
dictIntOptional <- map["dictIntOpt"]
dictIntImplicityUnwrapped <- map["dictIntImp"]
dictDouble <- map["dictDouble"]
dictDoubleOptional <- map["dictDoubleOpt"]
dictDoubleImplicityUnwrapped <- map["dictDoubleImp"]
dictFloat <- map["dictFloat"]
dictFloatOptional <- map["dictFloatOpt"]
dictFloatImplicityUnwrapped <- map["dictFloatImp"]
dictString <- map["dictString"]
dictStringOptional <- map["dictStringOpt"]
dictStringImplicityUnwrapped <- map["dictStringImp"]
dictAnyObject <- map["dictAnyObject"]
dictAnyObjectOptional <- map["dictAnyObjectOpt"]
dictAnyObjectImplicitlyUnwrapped <- map["dictAnyObjectImp"]
enumInt <- map["enumInt"]
enumIntOptional <- map["enumIntOpt"]
enumIntImplicitlyUnwrapped <- map["enumIntImp"]
enumDouble <- map["enumDouble"]
enumDoubleOptional <- map["enumDoubleOpt"]
enumDoubleImplicitlyUnwrapped <- map["enumDoubleImp"]
enumFloat <- map["enumFloat"]
enumFloatOptional <- map["enumFloatOpt"]
enumFloatImplicitlyUnwrapped <- map["enumFloatImp"]
enumString <- map["enumString"]
enumStringOptional <- map["enumStringOpt"]
enumStringImplicitlyUnwrapped <- map["enumStringImp"]
arrayEnumInt <- map["arrayEnumInt"]
arrayEnumIntOptional <- map["arrayEnumIntOpt"]
arrayEnumIntImplicitlyUnwrapped <- map["arrayEnumIntImp"]
dictEnumInt <- map["dictEnumInt"]
dictEnumIntOptional <- map["dictEnumIntOpt"]
dictEnumIntImplicitlyUnwrapped <- map["dictEnumIntImp"]
}
}
class TestCollectionOfPrimitives: Mappable {
var dictStringString: [String: String] = [:]
var dictStringInt: [String: Int] = [:]
var dictStringBool: [String: Bool] = [:]
var dictStringDouble: [String: Double] = [:]
var dictStringFloat: [String: Float] = [:]
var arrayString: [String] = []
var arrayInt: [Int] = []
var arrayBool: [Bool] = []
var arrayDouble: [Double] = []
var arrayFloat: [Float] = []
init(){
}
required init?(map: Map){
if map["value"].value() == nil {
}
if map.JSON["value"] == nil {
}
}
func mapping(map: Map) {
dictStringString <- map["dictStringString"]
dictStringBool <- map["dictStringBool"]
dictStringInt <- map["dictStringInt"]
dictStringDouble <- map["dictStringDouble"]
dictStringFloat <- map["dictStringFloat"]
arrayString <- map["arrayString"]
arrayInt <- map["arrayInt"]
arrayBool <- map["arrayBool"]
arrayDouble <- map["arrayDouble"]
arrayFloat <- map["arrayFloat"]
}
}
|
mit
|
784ec72f156ee883d0effafe6a6a3f12
| 34.035019 | 81 | 0.710684 | 3.831489 | false | false | false | false |
LuAndreCast/iOS_WatchProjects
|
watchOS3/HealthKit Workout/PhoneCommunicator.swift
|
1
|
9217
|
//
// PhoneCommunicator.swift
// HKworkout
//
// Created by Luis Castillo on 9/13/16.
// Copyright © 2016 LC. All rights reserved.
//
import Foundation
import WatchConnectivity
//MARK: - PhoneCommunicatorDelegate
@objc protocol PhoneCommunicatorDelegate {
func phoneCommunicator(watchStatesChanged:watchStates)
func phoneCommunicator(stateChanged:connectionState)
func phoneCommunicator(messageReceived:[String:Any]) -> [String : Any]
func phoneCommunicator(contextReceived:[String:Any])
}
@available(iOS 9.0, *)
@objc class PhoneCommunicator:NSObject, WCSessionDelegate
{
//MARK: - Properties
let wcSession:WCSession = WCSession.default()
var delegate:PhoneCommunicatorDelegate? = nil
var pendingStateToSend:[String] = [String]()
//MARK: - Setup
func setup()
{
if WCSession.isSupported()
{
self.setupSession()
}
else
{
delegate?.phoneCommunicator(stateChanged: connectionState.notSupported)
}
}//eom
private func setupSession()
{
wcSession.delegate = self
wcSession.activate()
}//eom
func session(_ session: WCSession,
activationDidCompleteWith activationState: WCSessionActivationState,
error: Error?)
{
if error != nil
{
print("error activationDidCompleteWith \(error?.localizedDescription)")
delegate?.phoneCommunicator(stateChanged: connectionState.unknownActivation)
}
else
{
switch activationState
{
case .activated:
delegate?.phoneCommunicator(stateChanged: connectionState.activated)
/* resending messages */
if pendingStateToSend.count > 0
{
for currState:String in pendingStateToSend
{
sendState(state: currState)
}//eofl
pendingStateToSend.removeAll()
}
break
case .inactive:
delegate?.phoneCommunicator(stateChanged: connectionState.inactive)
break
case .notActivated:
delegate?.phoneCommunicator(stateChanged: connectionState.notActivated)
break
}
}
}//eom
//MARK: - Watch States
func getWatchStates()->watchStates
{
let updatedStates:watchStates = getWatchStates(sessionProvided: nil)
return updatedStates
}//eom
private func getWatchStates(sessionProvided: WCSession?)->watchStates
{
var sessionChecking:WCSession = wcSession
if sessionProvided != nil { sessionChecking = sessionProvided! }
let watchState:watchStates = watchStates()
watchState.hasContentPending = sessionChecking.hasContentPending
watchState.isComplicationEnabled = sessionChecking.isComplicationEnabled
watchState.isPaired = sessionChecking.isPaired
watchState.isReachable = sessionChecking.isReachable
watchState.isWatchAppInstalled = sessionChecking.isWatchAppInstalled
let watchActivateState = sessionChecking.activationState
switch watchActivateState
{
case .activated:
watchState.state = connectionState.activated
break
case .notActivated:
watchState.state = connectionState.notActivated
break
case .inactive:
watchState.state = connectionState.inactive
break
}
return watchState
}//eom
//MARK: - States
func sessionDidDeactivate(_ session: WCSession) {
/* The `sessionDidDeactivate(_:)` callback indicates `WCSession` is finished delivering content to
the iOS app. iOS apps that process content delivered from their Watch Extension should finish
processing that content and call `activateSession()`. */
delegate?.phoneCommunicator(stateChanged: connectionState.deactivated)
}//eom
func sessionDidBecomeInactive(_ session: WCSession)
{
/* The `sessionDidBecomeInactive(_:)` callback indicates sending has been disabled. If your iOS app
sends content to its Watch extension it will need to stop trying at this point. */
delegate?.phoneCommunicator(stateChanged: connectionState.inactive)
}//eom
func sessionReachabilityDidChange(_ session: WCSession) {
if session.isReachable
{
delegate?.phoneCommunicator(stateChanged: connectionState.reachable)
}
else
{
delegate?.phoneCommunicator(stateChanged: connectionState.unreachable)
}
}//eom
func sessionWatchStateDidChange(_ session: WCSession)
{
let updatedStates = getWatchStates(sessionProvided: session)
delegate?.phoneCommunicator(watchStatesChanged: updatedStates)
}//eom
//MARK: - Interactive (LIVE) Messaging
func sendState(state:String,
resendAttempt:Bool = false)
{
let messageToSend = [key_state:state]
if wcSession.isReachable
{
wcSession.sendMessage(messageToSend, replyHandler: nil)
}
else
{
if resendAttempt
{
setupSession()
pendingStateToSend.append(state)
}
}
}//eom
func sendStateWithReply(state:String,
replyHander: @escaping ( ([String:Any])->Void),
errorHandler: @escaping ( (Error)->Void),
resendAttempt:Bool = false)
{
let messageToSend = [key_state:state]
if wcSession.isReachable
{
wcSession.sendMessage(messageToSend, replyHandler: replyHander, errorHandler: errorHandler)
}
else
{
if resendAttempt
{
setupSession()
pendingStateToSend.append(state)
}
else
{
errorHandler(error_unreachable)
}
}
}//eom
func sendMessage(messageToSend:[String:Any],
replyHander:@escaping (([String:Any])->Void),
errorHandler:@escaping ((Error)->Void) )
{
if wcSession.isReachable
{
wcSession.sendMessage(messageToSend, replyHandler: replyHander, errorHandler: errorHandler)
}
else
{
replyHander(["Reachable" : "False"])
errorHandler(error_unreachable)
}
}//eom
//MARK: delegates
// func session(_ session: WCSession,
// didReceiveMessage message: [String : Any]) {
// delegate?.phoneCommunicator(messageReceived: message)
// }//eom
func session(_ session: WCSession,
didReceiveMessage message: [String : Any],
replyHandler: @escaping ([String : Any]) -> Void) {
if delegate != nil
{
let replyMessage:[String : Any] = delegate!.phoneCommunicator(messageReceived: message)
// replyHandler([key_messageDelivery : 1])
replyHandler(replyMessage)
}
else
{
replyHandler([key_messageDelivery : 0])
}
}//eom
//MARK: - Application Context
func sendBackgroundContext(contextToSend:[String:Any], completion:( (Bool)->Void))
{
do
{
try wcSession.updateApplicationContext(contextToSend)
completion(true)
}
catch
{
print("error: \(error)")
completion(false)
}
}//eom
//MARK: delegates
func session(_ session: WCSession,
didReceiveApplicationContext applicationContext: [String : Any])
{
delegate?.phoneCommunicator(contextReceived: applicationContext)
}//eom
//MARK: - Transfers
func session(_ session: WCSession,
didFinish fileTransfer: WCSessionFileTransfer, error: Error?)
{
}//eom
func session(_ session: WCSession,
didReceive file: WCSessionFile)
{
}//eom
//MARK: - User Info
func session(_ session: WCSession,
didReceiveUserInfo userInfo: [String : Any] = [:])
{
//TODO: update me
}
func session(_ session: WCSession,
didFinish userInfoTransfer: WCSessionUserInfoTransfer,
error: Error?)
{
}//eom
//MARK: - Data
func session(_ session: WCSession,
didReceiveMessageData messageData: Data)
{
}//eom
func session(_ session: WCSession,
didReceiveMessageData messageData: Data,
replyHandler: @escaping (Data) -> Void)
{
}//eom
}//eoc
|
mit
|
8129929078c0b0c31b306e6fda576dcd
| 29.516556 | 108 | 0.571181 | 5.466192 | false | false | false | false |
angu/Kaning
|
Sources/Networking/NetworkManager.swift
|
1
|
4323
|
//
// NetworkManager.swift
// Kaning
//
// Created by Andrea Tullis on 24/04/2017.
//
//
import Foundation
import MultipeerConnectivity
public typealias PeerDiscoveredCallback = (_ peer: Peer) -> Void
public class NetworkManager: NSObject {
let displayName: String
let serviceType: String
let peerID: MCPeerID
let session: MCSession
fileprivate let serviceBrowser: MCNearbyServiceBrowser
fileprivate let serviceAdverstiser: MCNearbyServiceAdvertiser
var peers = [Peer]() {
didSet {
}
}
var newPeerCallback: PeerDiscoveredCallback?
public init(withName name: String, serviceType: String) {
displayName = name
self.serviceType = serviceType
peerID = MCPeerID(displayName: displayName)
serviceBrowser = MCNearbyServiceBrowser(peer: peerID, serviceType: serviceType)
serviceAdverstiser = MCNearbyServiceAdvertiser(peer: peerID, discoveryInfo: [:], serviceType: serviceType)
session = MCSession(peer: peerID)
}
deinit {
print("\(#file) - \(#function)")
serviceBrowser.stopBrowsingForPeers()
serviceAdverstiser.stopAdvertisingPeer()
session.disconnect()
}
public func start( peerDiscovered: @escaping PeerDiscoveredCallback) {
serviceBrowser.delegate = self
serviceAdverstiser.delegate = self
session.delegate = self
newPeerCallback = peerDiscovered
serviceAdverstiser.startAdvertisingPeer()
serviceBrowser.startBrowsingForPeers()
}
public func stop() {
serviceBrowser.stopBrowsingForPeers()
serviceAdverstiser.stopAdvertisingPeer()
}
}
extension NetworkManager : MCNearbyServiceBrowserDelegate {
public func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
print(#function)
browser.invitePeer(peerID, to: session, withContext: nil, timeout: 10)
}
public func browser(_ browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: Error) {
print(#function)
}
public func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
print(#function)
}
}
extension NetworkManager: MCNearbyServiceAdvertiserDelegate {
public func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) {
print(#function)
}
public func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) {
print(#function)
invitationHandler(true, session)
}
}
extension NetworkManager: MCSessionDelegate {
public func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
let peer = peers.first(where: {$0.peerID.displayName == peerID.displayName})
if let peer = peer {
peer.received?(data)
}
}
public func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
print("\(#function) - \(state.rawValue)")
if state == MCSessionState.connected {
let peer = Peer(withID: peerID, networkManager: self)
peers.append(peer)
newPeerCallback?(peer)
}
}
public func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
print(#function)
}
public func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
print(#function)
}
public func session(_ session: MCSession, didReceiveCertificate certificate: [Any]?, fromPeer peerID: MCPeerID, certificateHandler: @escaping (Bool) -> Void) {
print("\(#function) - \(String(describing: certificate))")
certificateHandler(true)
}
public func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL, withError error: Error?) {
print(#function)
}
}
|
apache-2.0
|
aca3c4cd850eb488f1fe2138e8c8f306
| 31.261194 | 201 | 0.676613 | 5.397004 | false | false | false | false |
exyte/Macaw
|
Source/model/draw/OffsetEffect.swift
|
1
|
243
|
open class OffsetEffect: Effect {
public let dx: Double
public let dy: Double
public init(dx: Double = 0, dy: Double = 0, input: Effect? = nil) {
self.dx = dx
self.dy = dy
super.init(input: input)
}
}
|
mit
|
0db239719d39312ef0d35a65cd30afc2
| 21.090909 | 71 | 0.567901 | 3.521739 | false | false | false | false |
younata/RSSClient
|
TethysAppSpecs/Easter Eggs/RogueLike/DirectionalGestureRecognizerSpec.swift
|
1
|
9062
|
import UIKit
import Quick
import Nimble
@testable import Tethys
final class DirectionalGestureRecognizerSpec: QuickSpec {
override func spec() {
var subject: DirectionalGestureRecognizer!
var observer: DirectionalGestureObserver!
var view: UIView!
beforeEach {
observer = DirectionalGestureObserver()
view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
subject = DirectionalGestureRecognizer(target: observer, action: #selector(DirectionalGestureObserver.didRecognize(_:)))
view.addGestureRecognizer(subject)
}
it("does not inform the gesture observer that anything happened yet") {
expect(observer.observations).to(beEmpty())
}
it("sets the gesture recognizer's state to possible") {
expect(subject.state).to(equal(.possible))
}
describe("when the user first taps") {
var touch: FakeTouch!
beforeEach {
touch = FakeTouch()
touch.currentLocation = CGPoint(x: 100, y: 100)
subject.touchesBegan([touch], with: UIEvent())
}
it("updates the gesture's current state to began") {
expect(subject.state).toEventually(equal(.began))
}
it("updates the observer") {
expect(observer.observations).toEventually(haveCount(1))
expect(observer.observations.last).to(equal(DirectionalGestureState(state: .began, direction: .zero)))
}
context("if the user lifts their finger now") {
beforeEach {
expect(observer.observations).toEventually(haveCount(1))
subject.touchesEnded([touch], with: UIEvent())
}
it("cancels the gesture recognizer") {
expect(subject.state).toEventually(equal(.possible))
}
it("updates the observer") {
expect(observer.observations).toEventually(haveCount(2))
expect(observer.observations.last).to(equal(DirectionalGestureState(state: .ended, direction: .zero)))
}
}
context("if the user moves their finger just a little bit") {
beforeEach {
expect(observer.observations).toEventually(haveCount(1))
touch.currentLocation = CGPoint(x: 130, y: 130)
subject.touchesMoved([touch], with: UIEvent())
}
it("doesn't do anything because the finger is within the deadzone") {
expect(subject.state).toEventually(equal(.began))
expect(observer.observations).to(haveCount(1))
}
}
context("if the user moves their finger outside the deadzone (to the right)") {
beforeEach {
expect(observer.observations).toEventually(haveCount(1))
touch.currentLocation = CGPoint(x: 150, y: 100)
subject.touchesMoved([touch], with: UIEvent())
}
it("marks the gesture as recognized") {
expect(subject.state).toEventually(equal(.changed))
}
it("sets the direction property") {
expect(subject.direction).toEventually(equal(CGVector(dx: 1, dy: 0)))
}
it("updates the observer") {
expect(observer.observations).toEventually(haveCount(2))
expect(observer.observations.last).to(equal(DirectionalGestureState(state: .changed, direction: CGVector(dx: 1, dy: 0))))
}
context("if the user moves their finger back into the deadzone") {
beforeEach {
expect(observer.observations).toEventually(haveCount(2))
touch.currentLocation = CGPoint(x: 120, y: 100)
subject.touchesMoved([touch], with: UIEvent())
}
it("keeps the gesture marked as recognized") {
expect(subject.state).toEventually(equal(.changed))
}
it("sets the direction property to zero") {
expect(subject.direction).toEventually(equal(CGVector(dx: 0, dy: 0)))
}
it("updates the observer") {
expect(observer.observations).toEventually(haveCount(3))
expect(observer.observations.last).to(equal(DirectionalGestureState(state: .changed, direction: .zero)))
}
}
context("if the user moves their finger to a different direction") {
beforeEach {
expect(observer.observations).toEventually(haveCount(2))
touch.currentLocation = CGPoint(x: 150, y: 150)
subject.touchesMoved([touch], with: UIEvent())
}
it("marks the gesture as changed") {
expect(subject.state).toEventually(equal(.changed))
}
it("sets the direction property to reflect the new direction") {
expect(subject.direction).toEventually(equal(CGVector(dx: sin(45.rads), dy: sin(45.rads))))
}
it("updates the observer") {
expect(observer.observations).toEventually(haveCount(3))
expect(observer.observations.last).to(equal(DirectionalGestureState(state: .changed, direction: CGVector(dx: sin(45.rads), dy: sin(45.rads)))))
}
}
context("if the user lifts their finger") {
beforeEach {
expect(observer.observations).toEventually(haveCount(2))
subject.touchesEnded([touch], with: UIEvent())
}
it("markse the gesture as ended") {
expect(subject.state).toEventually(equal(.possible))
}
it("sets the direction property to zero") {
expect(subject.direction).toEventually(equal(.zero))
}
it("updates the observer") {
expect(observer.observations).toEventually(haveCount(3))
expect(observer.observations.last).toEventually(equal(DirectionalGestureState(state: .ended, direction: .zero)))
}
}
}
}
}
}
extension UIGestureRecognizer.State: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .began: return ".began"
case .possible: return ".possible"
case .changed: return ".changed"
case .ended: return ".ended"
case .cancelled: return ".cancelled"
case .failed: return ".failed"
@unknown default:
return "UIGestureRecognizer.State Unknown!"
}
}
}
import XCTest
final class CGVectorLinearAlgebraSpec: XCTestCase {
func testNormalization() {
expect(CGVector(dx: 10, dy: 0).normalized()).to(equal(CGVector(dx: 1, dy: 0)))
expect(CGVector(dx: 0, dy: 5).normalized()).to(equal(CGVector(dx: 0, dy: 1)))
expect(CGVector(dx: 1, dy: 1).normalized()).to(equal(CGVector(dx: sin(45.rads), dy: sin(45.rads))))
}
func testPointSubtraction() {
expect(CGPoint(x: 10, y: 10) - CGPoint(x: 15, y: 17)).to(equal(CGVector(dx: -5, dy: -7)))
expect(CGPoint(x: 15, y: 17) - CGPoint(x: 11, y: 12)).to(equal(CGVector(dx: 4, dy: 5)))
}
func testPointVectorAddition() {
expect(CGPoint(x: 10, y: 10) + CGVector(dx: 5, dy: 2)).to(equal(CGPoint(x: 15, y: 12)))
var a = CGPoint(x: 10, y: 10)
a += CGVector(dx: 5, dy: 2)
expect(a).to(equal(CGPoint(x: 15, y: 12)))
}
func testPerformance() {
self.measure {
for _ in 0..<1_000 {
_ = CGVector(dx: 30000000, dy: 40000000).normalized()
}
}
}
}
extension Double {
var rads: Double {
return self * .pi / 180
}
}
struct DirectionalGestureState: Equatable {
let state: UIGestureRecognizer.State
let direction: CGVector
}
@objc final class DirectionalGestureObserver: NSObject {
var observations: [DirectionalGestureState] = []
@objc func didRecognize(_ gestureRecognizer: DirectionalGestureRecognizer) {
self.observations.append(DirectionalGestureState(state: gestureRecognizer.state, direction: gestureRecognizer.direction))
}
}
class FakeTouch: UITouch {
var currentLocation: CGPoint = .zero
override func location(in view: UIView?) -> CGPoint {
return self.currentLocation
}
}
|
mit
|
174b71d71f2c44cf00bb0a929ef6d2b9
| 37.726496 | 167 | 0.549768 | 4.970927 | false | false | false | false |
y0ke/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Managed Runtime/AAManagedTable.swift
|
2
|
18873
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
public class AAManagedTable {
//------------------------------------------------------------------------//
// Controller of table
public let controller: UIViewController
// Table view
public let style: AAContentTableStyle
public let tableView: UITableView
public var tableViewDelegate: UITableViewDelegate { get { return baseDelegate } }
public var tableViewDataSource: UITableViewDataSource { get { return baseDelegate } }
// Scrolling closure
public var tableScrollClosure: ((tableView: UITableView) -> ())?
// Is fade in/out animated
public var fadeShowing = false
// Sections of table
public var sections: [AAManagedSection] = [AAManagedSection]()
// Fixed Height
public var fixedHeight: CGFloat?
// Can Edit All rows
public var canEditAll: Bool?
// Can Delete All rows
public var canDeleteAll: Bool?
// Is Table in editing mode
public var isEditing: Bool {
get {
return tableView.editing
}
}
// Is updating sections
private var isUpdating = false
// Reference to table view delegate/data source
private var baseDelegate: AMBaseTableDelegate!
// Search
private var isSearchInited: Bool = false
private var isSearchAutoHide: Bool = false
private var searchDisplayController: UISearchDisplayController!
private var searchManagedController: AnyObject!
//------------------------------------------------------------------------//
public init(style: AAContentTableStyle, tableView: UITableView, controller: UIViewController) {
self.style = style
self.controller = controller
self.tableView = tableView
if style == .SettingsGrouped {
self.baseDelegate = AMGrouppedTableDelegate(data: self)
} else {
self.baseDelegate = AMPlainTableDelegate(data: self)
}
self.tableView.dataSource = self.baseDelegate
self.tableView.delegate = self.baseDelegate
}
//------------------------------------------------------------------------//
// Entry point to adding
public func beginUpdates() {
if isUpdating {
fatalError("Already updating table")
}
isUpdating = true
}
public func addSection(autoSeparator: Bool = false) -> AAManagedSection {
if !isUpdating {
fatalError("Table is not in updating mode")
}
let res = AAManagedSection(table: self, index: sections.count)
res.autoSeparators = autoSeparator
sections.append(res)
return res
}
public func search<C where C: AABindedSearchCell, C: UITableViewCell>(cell: C.Type, @noescape closure: (s: AAManagedSearchConfig<C>) -> ()) {
if !isUpdating {
fatalError("Table is not in updating mode")
}
if isSearchInited {
fatalError("Search already inited")
}
isSearchInited = true
// Configuring search source
let config = AAManagedSearchConfig<C>()
closure(s: config)
// Creating search source
let searchSource = AAManagedSearchController<C>(config: config, controller: controller, tableView: tableView)
self.searchDisplayController = searchSource.searchDisplay
self.searchManagedController = searchSource
self.isSearchAutoHide = config.isSearchAutoHide
}
public func endUpdates() {
if !isUpdating {
fatalError("Table is not in editable mode")
}
isUpdating = false
}
// Reloading table
public func reload() {
self.tableView.reloadData()
}
public func reload(section: Int) {
self.tableView.reloadSections(NSIndexSet(index: section), withRowAnimation: .Automatic)
}
// Binding methods
public func bind(binder: AABinder) {
for s in sections {
s.bind(self, binder: binder)
}
}
public func unbind(binder: AABinder) {
for s in sections {
s.unbind(self, binder: binder)
}
}
// Show/hide table
public func showTable() {
if isUpdating || !fadeShowing {
self.tableView.alpha = 1
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 1
})
}
}
public func hideTable() {
if isUpdating || !fadeShowing {
self.tableView.alpha = 0
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 0
})
}
}
// Controller callbacks
public func controllerViewWillDisappear(animated: Bool) {
// Auto close search on leaving controller
if isSearchAutoHide {
//dispatchOnUi { () -> Void in
searchDisplayController?.setActive(false, animated: false)
//}
}
}
public func controllerViewDidDisappear(animated: Bool) {
// Auto close search on leaving controller
// searchDisplayController?.setActive(false, animated: animated)
}
public func controllerViewWillAppear(animated: Bool) {
// Search bar dissapear fixing
// Hack No 1
if searchDisplayController != nil {
let searchBar = searchDisplayController!.searchBar
let superView = searchBar.superview
if !(superView is UITableView) {
searchBar.removeFromSuperview()
superView?.addSubview(searchBar)
}
}
// Hack No 2
tableView.tableHeaderView?.setNeedsLayout()
tableView.tableFooterView?.setNeedsLayout()
// Status bar styles
if (searchDisplayController != nil && searchDisplayController!.active) {
// If search is active: apply search status bar style
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.searchStatusBarStyle, animated: true)
} else {
// If search is not active: apply main status bar style
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.vcStatusBarStyle, animated: true)
}
}
}
// Closure based extension
public extension AAManagedTable {
public func section(closure: (s: AAManagedSection) -> ()){
closure(s: addSection(true))
}
}
// Table view delegates and data sources
private class AMPlainTableDelegate: AMBaseTableDelegate {
@objc func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(data.sections[section].headerHeight)
}
@objc func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat(data.sections[section].footerHeight)
}
@objc func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if (data.sections[section].headerText == nil) {
return UIView()
} else {
return nil
}
}
@objc func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if (data.sections[section].footerText == nil) {
return UIView()
} else {
return nil
}
}
}
private class AMGrouppedTableDelegate: AMBaseTableDelegate {
@objc func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = ActorSDK.sharedActor().style.cellHeaderColor
}
@objc func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = ActorSDK.sharedActor().style.cellFooterColor
}
}
private class AMBaseTableDelegate: NSObject, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
unowned private let data: AAManagedTable
init(data: AAManagedTable) {
self.data = data
}
@objc func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.sections.count
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.sections[section].numberOfItems(data)
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return data.sections[indexPath.section].cellForItem(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let text = data.sections[section].headerText
if text != nil {
return AALocalized(text!)
} else {
return text
}
}
@objc func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
let text = data.sections[section].footerText
if text != nil {
return AALocalized(text!)
} else {
return text
}
}
@objc func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if data.fixedHeight != nil {
return data.fixedHeight!
}
return data.sections[indexPath.section].cellHeightForItem(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if data.canEditAll != nil {
return data.canEditAll!
}
return (data.sections[indexPath.section].numberOfItems(data) > 0 ? data.sections[indexPath.section].canDelete(data, indexPath: indexPath) : false)
}
@objc func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
@objc func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if data.canDeleteAll != nil {
if data.canDeleteAll! {
return .Delete
} else {
return .None
}
}
return data.sections[indexPath.section].canDelete(data, indexPath: indexPath) ? .Delete : .None
}
@objc func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
return data.sections[indexPath.section].delete(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = data.sections[indexPath.section]
if section.canSelect(data, indexPath: indexPath) {
if section.select(data, indexPath: indexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} else {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
@objc func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if action == "copy:" {
let section = data.sections[indexPath.section]
return section.canCopy(data, indexPath: indexPath)
}
return false
}
@objc func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let section = data.sections[indexPath.section]
return section.canCopy(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
if action == "copy:" {
let section = data.sections[indexPath.section]
if section.canCopy(data, indexPath: indexPath) {
section.copy(data, indexPath: indexPath)
}
}
}
@objc func scrollViewDidScroll(scrollView: UIScrollView) {
if (data.tableView == scrollView) {
data.tableScrollClosure?(tableView: data.tableView)
}
}
}
public class AAManagedSearchConfig<BindCell where BindCell: AABindedSearchCell, BindCell: UITableViewCell> {
public var searchList: ARBindedDisplayList!
public var selectAction: ((BindCell.BindData) -> ())?
public var isSearchAutoHide: Bool = true
public var didBind: ((c: BindCell, d: BindCell.BindData) -> ())?
}
private class AAManagedSearchController<BindCell where BindCell: AABindedSearchCell, BindCell: UITableViewCell>: NSObject, UISearchBarDelegate, UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate, ARDisplayList_Listener {
let config: AAManagedSearchConfig<BindCell>
let displayList: ARBindedDisplayList
let searchDisplay: UISearchDisplayController
init(config: AAManagedSearchConfig<BindCell>, controller: UIViewController, tableView: UITableView) {
self.config = config
self.displayList = config.searchList
let style = ActorSDK.sharedActor().style
let searchBar = UISearchBar()
// Styling Search bar
searchBar.searchBarStyle = UISearchBarStyle.Default
searchBar.translucent = false
searchBar.placeholder = "" // SearchBar placeholder animation fix
// SearchBar background color
searchBar.barTintColor = style.searchBackgroundColor.forTransparentBar()
searchBar.setBackgroundImage(Imaging.imageWithColor(style.searchBackgroundColor, size: CGSize(width: 1, height: 1)), forBarPosition: .Any, barMetrics: .Default)
searchBar.backgroundColor = style.searchBackgroundColor
// SearchBar cancel color
searchBar.tintColor = style.searchCancelColor
// Apply keyboard color
searchBar.keyboardAppearance = style.isDarkApp ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
// SearchBar field color
let fieldBg = Imaging.imageWithColor(style.searchFieldBgColor, size: CGSize(width: 14,height: 28))
.roundCorners(14, h: 28, roundSize: 4)
searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImageWithLeftCapWidth(7, topCapHeight: 0), forState: UIControlState.Normal)
// SearchBar field text color
for subView in searchBar.subviews {
for secondLevelSubview in subView.subviews {
if let tf = secondLevelSubview as? UITextField {
tf.textColor = style.searchFieldTextColor
break
}
}
}
self.searchDisplay = UISearchDisplayController(searchBar: searchBar, contentsController: controller)
super.init()
// Creating Search Display Controller
self.searchDisplay.searchBar.delegate = self
self.searchDisplay.searchResultsDataSource = self
self.searchDisplay.searchResultsDelegate = self
self.searchDisplay.delegate = self
// Styling search list
self.searchDisplay.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.searchDisplay.searchResultsTableView.backgroundColor = ActorSDK.sharedActor().style.vcBgColor
// Adding search to table header
let header = AATableViewHeader(frame: CGRectMake(0, 0, 320, 44))
header.addSubview(self.searchDisplay.searchBar)
tableView.tableHeaderView = header
// Start receiving events
self.displayList.addListener(self)
}
// Model
func objectAtIndexPath(indexPath: NSIndexPath) -> BindCell.BindData {
return displayList.itemWithIndex(jint(indexPath.row)) as! BindCell.BindData
}
@objc func onCollectionChanged() {
searchDisplay.searchResultsTableView.reloadData()
}
// Table view data
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(displayList.size());
}
@objc func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let item = objectAtIndexPath(indexPath)
return BindCell.self.bindedCellHeight(item)
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = objectAtIndexPath(indexPath)
let cell = tableView.dequeueCell(BindCell.self, indexPath: indexPath) as! BindCell
cell.bind(item, search: nil)
return cell
}
@objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = objectAtIndexPath(indexPath)
config.selectAction!(item)
// MainAppTheme.navigation.applyStatusBar()
}
// Search updating
@objc func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let normalized = searchText.trim().lowercaseString
if (normalized.length > 0) {
displayList.initSearchWithQuery(normalized, withRefresh: false)
} else {
displayList.initEmpty()
}
}
// Search styling
@objc func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.searchStatusBarStyle, animated: true)
}
@objc func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController) {
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.vcStatusBarStyle, animated: true)
}
@objc func searchDisplayController(controller: UISearchDisplayController, didShowSearchResultsTableView tableView: UITableView) {
for v in tableView.subviews {
if (v is UIImageView) {
(v as! UIImageView).alpha = 0;
}
}
}
}
|
agpl-3.0
|
6cd9496530ead6f7d8da522009676683
| 33.314545 | 237 | 0.633074 | 5.524883 | false | false | false | false |
Pluto-Y/SwiftyEcharts
|
SwiftyEchartsTest_iOS/AnimatableSpec.swift
|
1
|
8398
|
//
// AnimatableSpec.swift
// SwiftyEcharts
//
// Created by Pluto Y on 22/03/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import UIKit
import Quick
import Nimble
@testable import SwiftyEcharts
class AnimatableSpec: QuickSpec {
override func spec() {
describe("For type enum Time") {
beforeEach {
JsCache.removeAll()
}
it(" needs to check the jsonString for Time ") {
let function: Function = "function (idx) {return idx * 0.65;}"
let numberTime = Time.number(3.14)
let functionTime = Time.function(function)
expect(numberTime.jsonString).to(equal("3.14"))
expect(functionTime.jsonString).to(equal(function.jsonString))
}
it(" needs to check the convertiable for Time ") {
let function: Function = "function (idx) {return idx * 100;}"
let floatTime: Time = 100.0
let intTime: Time = 85
let functionTime: Time = Time.function(function)
expect(floatTime.jsonString).to(equal(Time.number(100.0).jsonString))
expect(intTime.jsonString).to(equal(Time.number(85).jsonString))
expect(functionTime.jsonString).to(equal(function.jsonString))
}
}
describe("For type enum EasingFunction") {
let linearString = "linear"
let quadraticInString = "quadraticIn"
let quadraticOutString = "quadraticOut"
let quadraticInOutString = "quadraticInOut"
let cubicInString = "cubicIn"
let cubicOutString = "cubicOut"
let cubicInOutString = "cubicInOut"
let quarticInString = "quarticIn"
let quarticOutString = "quarticOut"
let quarticInOutString = "quarticInOut"
let quinticInString = "quinticIn"
let quinticOutString = "quinticOut"
let quinticInOutString = "quinticInOut"
let sinusoidalInString = "sinusoidalIn"
let sinusoidalOutString = "sinusoidalOut"
let sinusoidalInOutString = "sinusoidalInOut"
let exponentialInString = "exponentialIn"
let exponentialOutString = "exponentialOut"
let exponentialInOutString = "exponentialInOut"
let circularInString = "circularIn"
let circularOutString = "circularOut"
let circularInOutString = "circularInOut"
let elasticInString = "elasticIn"
let elasticOutString = "elasticOut"
let elasticInOutString = "elasticInOut"
let backInString = "backIn"
let backOutString = "backOut"
let backInOutString = "backInOut"
let bounceInString = "bounceIn"
let bounceOutString = "bounceOut"
let bounceInOutString = "bounceInOut"
let linearEasingFunction = EasingFunction.linear
let quadraticInEasingFunction = EasingFunction.quadraticIn
let quadraticOutEasingFunction = EasingFunction.quadraticOut
let quadraticInOutEasingFunction = EasingFunction.quadraticInOut
let cubicInEasingFunction = EasingFunction.cubicIn
let cubicOutEasingFunction = EasingFunction.cubicOut
let cubicInOutEasingFunction = EasingFunction.cubicInOut
let quarticInEasingFunction = EasingFunction.quarticIn
let quarticOutEasingFunction = EasingFunction.quarticOut
let quarticInOutEasingFunction = EasingFunction.quarticInOut
let quinticInEasingFunction = EasingFunction.quinticIn
let quinticOutEasingFunction = EasingFunction.quinticOut
let quinticInOutEasingFunction = EasingFunction.quinticInOut
let sinusoidalInEasingFunction = EasingFunction.sinusoidalIn
let sinusoidalOutEasingFunction = EasingFunction.sinusoidalOut
let sinusoidalInOutEasingFunction = EasingFunction.sinusoidalInOut
let exponentialInEasingFunction = EasingFunction.exponentialIn
let exponentialOutEasingFunction = EasingFunction.exponentialOut
let exponentialInOutEasingFunction = EasingFunction.exponentialInOut
let circularInEasingFunction = EasingFunction.circularIn
let circularOutEasingFunction = EasingFunction.circularOut
let circularInOutEasingFunction = EasingFunction.circularInOut
let elasticInEasingFunction = EasingFunction.elasticIn
let elasticOutEasingFunction = EasingFunction.elasticOut
let elasticInOutEasingFunction = EasingFunction.elasticInOut
let backInEasingFunction = EasingFunction.backIn
let backOutEasingFunction = EasingFunction.backOut
let backInOutEasingFunction = EasingFunction.backInOut
let bounceInEasingFunction = EasingFunction.bounceIn
let bounceOutEasingFunction = EasingFunction.bounceOut
let bounceInOutEasingFunction = EasingFunction.bounceInOut
it(" needs to check the jsonString ") {
expect(linearEasingFunction.jsonString).to(equal(linearString.jsonString))
expect(quadraticInEasingFunction.jsonString).to(equal(quadraticInString.jsonString))
expect(quadraticOutEasingFunction.jsonString).to(equal(quadraticOutString.jsonString))
expect(quadraticInOutEasingFunction.jsonString).to(equal(quadraticInOutString.jsonString))
expect(cubicInEasingFunction.jsonString).to(equal(cubicInString.jsonString))
expect(cubicOutEasingFunction.jsonString).to(equal(cubicOutString.jsonString))
expect(cubicInOutEasingFunction.jsonString).to(equal(cubicInOutString.jsonString))
expect(quarticInEasingFunction.jsonString).to(equal(quarticInString.jsonString))
expect(quarticOutEasingFunction.jsonString).to(equal(quarticOutString.jsonString))
expect(quarticInOutEasingFunction.jsonString).to(equal(quarticInOutString.jsonString))
expect(quinticInEasingFunction.jsonString).to(equal(quinticInString.jsonString))
expect(quinticOutEasingFunction.jsonString).to(equal(quinticOutString.jsonString))
expect(quinticInOutEasingFunction.jsonString).to(equal(quinticInOutString.jsonString))
expect(sinusoidalInEasingFunction.jsonString).to(equal(sinusoidalInString.jsonString))
expect(sinusoidalOutEasingFunction.jsonString).to(equal(sinusoidalOutString.jsonString))
expect(sinusoidalInOutEasingFunction.jsonString).to(equal(sinusoidalInOutString.jsonString))
expect(exponentialInEasingFunction.jsonString).to(equal(exponentialInString.jsonString))
expect(exponentialOutEasingFunction.jsonString).to(equal(exponentialOutString.jsonString))
expect(exponentialInOutEasingFunction.jsonString).to(equal(exponentialInOutString.jsonString))
expect(circularInEasingFunction.jsonString).to(equal(circularInString.jsonString))
expect(circularOutEasingFunction.jsonString).to(equal(circularOutString.jsonString))
expect(circularInOutEasingFunction.jsonString).to(equal(circularInOutString.jsonString))
expect(elasticInEasingFunction.jsonString).to(equal(elasticInString.jsonString))
expect(elasticOutEasingFunction.jsonString).to(equal(elasticOutString.jsonString))
expect(elasticInOutEasingFunction.jsonString).to(equal(elasticInOutString.jsonString))
expect(backInEasingFunction.jsonString).to(equal(backInString.jsonString))
expect(backOutEasingFunction.jsonString).to(equal(backOutString.jsonString))
expect(backInOutEasingFunction.jsonString).to(equal(backInOutString.jsonString))
expect(bounceInEasingFunction.jsonString).to(equal(bounceInString.jsonString))
expect(bounceOutEasingFunction.jsonString).to(equal(bounceOutString.jsonString))
expect(bounceInOutEasingFunction.jsonString).to(equal(bounceInOutString.jsonString))
}
}
}
}
|
mit
|
2677a3c7144676e25542c423fcf24ca6
| 58.133803 | 110 | 0.678933 | 5.034173 | false | false | false | false |
uasys/swift
|
test/SILOptimizer/mandatory_inlining.swift
|
1
|
4559
|
// RUN: %target-swift-frontend -enable-sil-ownership -sil-verify-all -primary-file %s -emit-sil -o - -verify | %FileCheck %s
// These tests are deliberately shallow, because I do not want to depend on the
// specifics of SIL generation, which might change for reasons unrelated to this
// pass
func foo(_ x: Float) -> Float {
return bar(x);
}
// CHECK-LABEL: sil hidden @_T018mandatory_inlining3foo{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $Float):
// CHECK-NEXT: debug_value %0 : $Float, let, name "x"
// CHECK-NEXT: return %0
@_transparent func bar(_ x: Float) -> Float {
return baz(x)
}
// CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3bar{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: return
@_transparent func baz(_ x: Float) -> Float {
return x
}
// CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3baz{{[_0-9a-zA-Z]*}}F
// CHECK: return
func spam(_ x: Int) -> Int {
return x
}
// CHECK-LABEL: sil hidden @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
@_transparent func ham(_ x: Int) -> Int {
return spam(x)
}
// CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining3ham{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK: return
func eggs(_ x: Int) -> Int {
return ham(x)
}
// CHECK-LABEL: sil hidden @_T018mandatory_inlining4eggs{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @_T018mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK: return
@_transparent func call_auto_closure(_ x: @autoclosure () -> Bool) -> Bool {
return x()
}
func test_auto_closure_with_capture(_ x: Bool) -> Bool {
return call_auto_closure(x)
}
// This should be fully inlined and simply return x; however, there's a lot of
// non-SSA cruft that I don't want this test to depend on, so I'm just going
// to verify that it doesn't have any function applications left
// CHECK-LABEL: sil hidden @{{.*}}test_auto_closure_with_capture
// CHECK-NOT: = apply
// CHECK: return
func test_auto_closure_without_capture() -> Bool {
return call_auto_closure(false)
}
// This should be fully inlined and simply return false, which is easier to check for
// CHECK-LABEL: sil hidden @_T018mandatory_inlining33test_auto_closure_without_captureSbyF
// CHECK: [[FV:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: [[FALSE:%.*]] = struct $Bool ([[FV:%.*]] : $Builtin.Int1)
// CHECK: return [[FALSE]]
infix operator &&& : LogicalConjunctionPrecedence
infix operator ||| : LogicalDisjunctionPrecedence
@_transparent func &&& (lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool {
if lhs {
return rhs()
}
return false
}
@_transparent func ||| (lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool {
if lhs {
return true
}
return rhs()
}
func test_chained_short_circuit(_ x: Bool, y: Bool, z: Bool) -> Bool {
return x &&& (y ||| z)
}
// The test below just makes sure there are no uninlined [transparent] calls
// left (i.e. the autoclosure and the short-circuiting boolean operators are
// recursively inlined properly)
// CHECK-LABEL: sil hidden @_T018mandatory_inlining26test_chained_short_circuit{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: = apply [transparent]
// CHECK: return
// Union element constructors should be inlined automatically.
enum X {
case onetransp
case twotransp
}
func testInlineUnionElement() -> X {
return X.onetransp
// CHECK-LABEL: sil hidden @_T018mandatory_inlining22testInlineUnionElementAA1XOyF
// CHECK: enum $X, #X.onetransp!enumelt
// CHECK-NOT: = apply
// CHECK: return
}
@_transparent
func call_let_auto_closure(_ x: @autoclosure () -> Bool) -> Bool {
return x()
}
// CHECK: sil hidden @{{.*}}test_let_auto_closure_with_value_capture
// CHECK: bb0(%0 : $Bool):
// CHECK-NEXT: debug_value %0 : $Bool
// CHECK-NEXT: return %0 : $Bool
func test_let_auto_closure_with_value_capture(_ x: Bool) -> Bool {
return call_let_auto_closure(x)
}
class C {}
// CHECK-LABEL: sil hidden [transparent] @_T018mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F
@_transparent
func class_constrained_generic<T : C>(_ o: T) -> AnyClass? {
// CHECK: return
return T.self
}
// CHECK-LABEL: sil hidden @_T018mandatory_inlining6invokeyAA1CCF : $@convention(thin) (@owned C) -> () {
func invoke(_ c: C) {
// CHECK-NOT: function_ref @_T018mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: apply
// CHECK: init_existential_metatype
_ = class_constrained_generic(c)
// CHECK: return
}
|
apache-2.0
|
0f11a10e5f447b26aa689c26391451f7
| 27.141975 | 124 | 0.668787 | 3.188112 | false | true | false | false |
apple/swift
|
test/IDE/print_ast_tc_decls.swift
|
2
|
57607
|
// RUN: %empty-directory(%t)
//
// Build swift modules this test depends on.
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/foo_swift_module.swift -enable-objc-interop -disable-objc-attr-requires-foundation-module
//
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift -enable-objc-interop -disable-objc-attr-requires-foundation-module
// FIXME: END -enable-source-import hackaround
//
// This file should not have any syntax or type checker errors.
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -D ERRORS -typecheck -verify %s -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefixes=PASS_PRINT_AST,PASS_PRINT_AST_TYPE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefixes=PASS_PRINT_AST,PASS_PRINT_AST_TYPEREPR -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPEREPR -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -emit-module -o %t -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module %s
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_NO_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200_DESERIALIZED -strict-whitespace < %t.printed.txt
// FIXME: rdar://15167697
// FIXME: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -enable-objc-interop -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_IF_AMBIGUOUS -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt
// FIXME: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// REQUIRES: objc_interop
import Bar
import ObjectiveC
import class Foo.FooClassBase
import struct Foo.FooStruct1
import func Foo.fooFunc1
@_exported import FooHelper
import foo_swift_module
// FIXME: enum tests
//import enum FooClangModule.FooEnum1
// PASS_COMMON: {{^}}import Bar{{$}}
// PASS_COMMON: {{^}}import class Foo.FooClassBase{{$}}
// PASS_COMMON: {{^}}import struct Foo.FooStruct1{{$}}
// PASS_COMMON: {{^}}import func Foo.fooFunc1{{$}}
// PASS_COMMON: {{^}}@_exported import FooHelper{{$}}
// PASS_COMMON: {{^}}import foo_swift_module{{$}}
//===---
//===--- Helper types.
//===---
struct FooStruct {}
class FooClass {}
class BarClass {}
protocol FooProtocol {}
protocol BarProtocol {}
protocol BazProtocol { func baz() }
protocol QuxProtocol {
associatedtype Qux
}
protocol SubFooProtocol : FooProtocol { }
class FooProtocolImpl : FooProtocol {}
class FooBarProtocolImpl : FooProtocol, BarProtocol {}
class BazProtocolImpl : BazProtocol { func baz() {} }
//===---
//===--- Basic smoketest.
//===---
struct d0100_FooStruct {
// PASS_COMMON-LABEL: {{^}}struct d0100_FooStruct {{{$}}
var instanceVar1: Int = 0
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue var instanceVar1: Int{{$}}
var computedProp1: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} var computedProp1: Int { get }{{$}}
func instanceFunc0() {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc0(){{$}}
func instanceFunc1(a: Int) {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc1(a: Int){{$}}
func instanceFunc2(a: Int, b: inout Double) {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc2(a: Int, b: inout Double){{$}}
func instanceFunc3(a: Int, b: Double) { var a = a; a = 1; _ = a }
// PASS_COMMON-NEXT: {{^}} func instanceFunc3(a: Int, b: Double){{$}}
func instanceFuncWithDefaultArg1(a: Int = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg1(a: Int = 0){{$}}
func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0){{$}}
func varargInstanceFunc0(v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc0(v: Int...){{$}}
func varargInstanceFunc1(a: Float, v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc1(a: Float, v: Int...){{$}}
func varargInstanceFunc2(a: Float, b: Double, v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc2(a: Float, b: Double, v: Int...){{$}}
func overloadedInstanceFunc1() -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Int{{$}}
func overloadedInstanceFunc1() -> Double { return 0.0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Double{{$}}
func overloadedInstanceFunc2(x: Int) -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Int) -> Int{{$}}
func overloadedInstanceFunc2(x: Double) -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Double) -> Int{{$}}
func builderFunc1(a: Int) -> d0100_FooStruct { return d0100_FooStruct(); }
// PASS_COMMON-NEXT: {{^}} func builderFunc1(a: Int) -> d0100_FooStruct{{$}}
subscript(i: Int) -> Double {
get {
return Double(i)
}
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Double { get }{{$}}
subscript(i: Int, j: Int) -> Double {
get {
return Double(i + j)
}
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int, j: Int) -> Double { get }{{$}}
static subscript(i: Int) -> Double {
get {
return Double(i)
}
}
// PASS_COMMON-NEXT: {{^}} static subscript(i: Int) -> Double { get }{{$}}
func bodyNameVoidFunc1(a: Int, b x: Float) {}
// PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc1(a: Int, b x: Float){{$}}
func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double) {}
// PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double){{$}}
func bodyNameStringFunc1(a: Int, b x: Float) -> String { return "" }
// PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc1(a: Int, b x: Float) -> String{{$}}
func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String { return "" }
// PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String{{$}}
struct NestedStruct {}
// PASS_COMMON-NEXT: {{^}} struct NestedStruct {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class NestedClass {}
// PASS_COMMON-NEXT: {{^}} class NestedClass {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum NestedEnum {}
// PASS_COMMON-NEXT: {{^}} enum NestedEnum {{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
// Cannot declare a nested protocol.
// protocol NestedProtocol {}
typealias NestedTypealias = Int
// PASS_COMMON-NEXT: {{^}} typealias NestedTypealias = Int{{$}}
static var staticVar1: Int = 42
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue static var staticVar1: Int{{$}}
static var computedStaticProp1: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} static var computedStaticProp1: Int { get }{{$}}
static func staticFunc0() {}
// PASS_COMMON-NEXT: {{^}} static func staticFunc0(){{$}}
static func staticFunc1(a: Int) {}
// PASS_COMMON-NEXT: {{^}} static func staticFunc1(a: Int){{$}}
static func overloadedStaticFunc1() -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Int{{$}}
static func overloadedStaticFunc1() -> Double { return 0.0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Double{{$}}
static func overloadedStaticFunc2(x: Int) -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Int) -> Int{{$}}
static func overloadedStaticFunc2(x: Double) -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Double) -> Int{{$}}
}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} init(instanceVar1: Int = 0){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
extension d0100_FooStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct {{{$}}
var extProp: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} var extProp: Int { get }{{$}}
func extFunc0() {}
// PASS_COMMON-NEXT: {{^}} func extFunc0(){{$}}
static var extStaticProp: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} static var extStaticProp: Int { get }{{$}}
static func extStaticFunc0() {}
// PASS_COMMON-NEXT: {{^}} static func extStaticFunc0(){{$}}
struct ExtNestedStruct {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class ExtNestedClass {}
// PASS_COMMON-NEXT: {{^}} class ExtNestedClass {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum ExtNestedEnum {
case ExtEnumX(Int)
}
// PASS_COMMON-NEXT: {{^}} enum ExtNestedEnum {{{$}}
// PASS_COMMON-NEXT: {{^}} case ExtEnumX(Int){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
typealias ExtNestedTypealias = Int
// PASS_COMMON-NEXT: {{^}} typealias ExtNestedTypealias = Int{{$}}
}
// PASS_COMMON-NEXT: {{^}}}{{$}}
extension d0100_FooStruct.NestedStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.NestedStruct {{{$}}
struct ExtNestedStruct2 {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct2 {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
}
extension d0100_FooStruct.ExtNestedStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.ExtNestedStruct {{{$}}
struct ExtNestedStruct3 {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct3 {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
}
// PASS_COMMON-NEXT: {{^}}}{{$}}
var fooObject: d0100_FooStruct = d0100_FooStruct()
// PASS_ONE_LINE-DAG: {{^}}@_hasInitialValue var fooObject: d0100_FooStruct{{$}}
struct d0110_ReadWriteProperties {
// PASS_RW_PROP_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}}
// PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}}
var computedProp1: Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp1: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp1: Int{{$}}
subscript(i: Int) -> Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int{{$}}
static var computedStaticProp1: Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int{{$}}
var computedProp2: Int {
mutating get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}}
var computedProp3: Int {
get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}}
var computedProp4: Int {
mutating get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}}
subscript(i: Float) -> Int {
get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} init(){{$}}
// PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} init(){{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}}
extension d0110_ReadWriteProperties {
// PASS_RW_PROP_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}}
// PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}}
var extProp: Int {
get {
return 42
}
set(v) {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var extProp: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var extProp: Int{{$}}
static var extStaticProp: Int {
get {
return 42
}
set(v) {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} static var extStaticProp: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var extStaticProp: Int{{$}}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}}
class d0120_TestClassBase {
// PASS_COMMON-LABEL: {{^}}class d0120_TestClassBase {{{$}}
required init() {}
// PASS_COMMON-NEXT: {{^}} required init(){{$}}
init?(fail: String) {}
// PASS_COMMON-NEXT: {{^}} init?(fail: String){{$}}
init!(iuoFail: String) {}
// PASS_COMMON-NEXT: {{^}} init!(iuoFail: String){{$}}
final func baseFunc1() {}
// PASS_COMMON-NEXT: {{^}} final func baseFunc1(){{$}}
func baseFunc2() {}
// PASS_COMMON-NEXT: {{^}} func baseFunc2(){{$}}
subscript(i: Int) -> Int {
return 0
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Int { get }{{$}}
class var baseClassVar1: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} class var baseClassVar1: Int { get }{{$}}
// FIXME: final class var not allowed to have storage, but static is?
#if ERRORS
final class var baseClassVar2: Int = 0
// expected-error@-1 {{class stored properties not supported in classes; did you mean 'static'?}}
#endif
final class var baseClassVar3: Int { return 0 }
// PASS_COMMON: {{^}} final class var baseClassVar3: Int { get }{{$}}
static var baseClassVar4: Int = 0
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue static var baseClassVar4: Int{{$}}
static var baseClassVar5: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static var baseClassVar5: Int { get }{{$}}
class func baseClassFunc1() {}
// PASS_COMMON-NEXT: {{^}} class func baseClassFunc1(){{$}}
final class func baseClassFunc2() {}
// PASS_COMMON-NEXT: {{^}} final class func baseClassFunc2(){{$}}
static func baseClassFunc3() {}
// PASS_COMMON-NEXT: {{^}} static func baseClassFunc3(){{$}}
}
class d0121_TestClassDerived : d0120_TestClassBase {
// PASS_COMMON-LABEL: {{^}}@_inheritsConvenienceInitializers {{()?}}class d0121_TestClassDerived : d0120_TestClassBase {{{$}}
required init() { super.init() }
// PASS_COMMON-NEXT: {{^}} required init(){{$}}
override init?(fail: String) { nil }
// PASS_COMMON-NEXT: {{^}} override init?(fail: String){{$}}
override init!(iuoFail: String) { nil }
// PASS_COMMON-NEXT: {{^}} override init!(iuoFail: String){{$}}
final override func baseFunc2() {}
// PASS_COMMON-NEXT: {{^}} {{(override |final )+}}func baseFunc2(){{$}}
override final subscript(i: Int) -> Int {
return 0
}
// PASS_COMMON-NEXT: {{^}} override final subscript(i: Int) -> Int { get }{{$}}
}
protocol d0130_TestProtocol {
// PASS_COMMON-LABEL: {{^}}protocol d0130_TestProtocol {{{$}}
associatedtype NestedTypealias
// PASS_COMMON-NEXT: {{^}} associatedtype NestedTypealias{{$}}
var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} var property1: Int { get }{{$}}
var property2: Int { get set }
// PASS_COMMON-NEXT: {{^}} var property2: Int { get set }{{$}}
func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} func protocolFunc1(){{$}}
}
@objc protocol d0140_TestObjCProtocol {
// PASS_COMMON-LABEL: {{^}}@objc protocol d0140_TestObjCProtocol {{{$}}
@objc optional var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} @objc optional var property1: Int { get }{{$}}
@objc optional func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} @objc optional func protocolFunc1(){{$}}
}
protocol d0150_TestClassProtocol : class {}
// PASS_COMMON-LABEL: {{^}}protocol d0150_TestClassProtocol : AnyObject {{{$}}
@objc protocol d0151_TestClassProtocol {}
// PASS_COMMON-LABEL: {{^}}@objc protocol d0151_TestClassProtocol {{{$}}
class d0170_TestAvailability {
// PASS_COMMON-LABEL: {{^}}class d0170_TestAvailability {{{$}}
@available(*, unavailable)
func f1() {}
// PASS_COMMON-NEXT: {{^}} @available(*, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f1(){{$}}
@available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee")
func f2() {}
// PASS_COMMON-NEXT: {{^}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee"){{$}}
// PASS_COMMON-NEXT: {{^}} func f2(){{$}}
@available(iOS, unavailable)
@available(OSX, unavailable)
func f3() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} @available(macOS, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f3(){{$}}
@available(iOS 8.0, OSX 10.10, *)
func f4() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, macOS 10.10, *){{$}}
// PASS_COMMON-NEXT: {{^}} func f4(){{$}}
// Convert long-form @available() to short form when possible.
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.10)
func f5() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, macOS 10.10, *){{$}}
// PASS_COMMON-NEXT: {{^}} func f5(){{$}}
}
@objc class d0180_TestIBAttrs {
// PASS_COMMON-LABEL: {{^}}@objc class d0180_TestIBAttrs {{{$}}
@IBAction func anAction(_: AnyObject) {}
// PASS_COMMON-NEXT: {{^}} @objc @IBAction @MainActor func anAction(_: AnyObject){{$}}
@IBSegueAction func aSegueAction(_ coder: AnyObject, sender: AnyObject, identifier: AnyObject?) -> Any? { fatalError() }
// PASS_COMMON-NEXT: {{^}} @objc @IBSegueAction func aSegueAction(_ coder: AnyObject, sender: AnyObject, identifier: AnyObject?) -> Any?{{$}}
@IBDesignable
class ADesignableClass {}
// PASS_COMMON-NEXT: {{^}} @IBDesignable class ADesignableClass {{{$}}
}
@objc class d0181_TestIBAttrs {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}@objc class d0181_TestIBAttrs {{{$}}
@IBOutlet weak var anOutlet: d0181_TestIBAttrs!
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @IBOutlet @_hasInitialValue weak var anOutlet: @sil_weak d0181_TestIBAttrs!{{$}}
@IBInspectable var inspectableProp: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @IBInspectable @_hasInitialValue var inspectableProp: Int{{$}}
@GKInspectable var inspectableProp2: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @GKInspectable @_hasInitialValue var inspectableProp2: Int{{$}}
}
struct d0190_LetVarDecls {
// PASS_PRINT_AST-LABEL: {{^}}struct d0190_LetVarDecls {{{$}}
// PASS_PRINT_MODULE_INTERFACE-LABEL: {{^}}struct d0190_LetVarDecls {{{$}}
let instanceVar1: Int = 0
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue let instanceVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue let instanceVar1: Int{{$}}
let instanceVar2 = 0
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue let instanceVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue let instanceVar2: Int{{$}}
static let staticVar1: Int = 42
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue static let staticVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue static let staticVar1: Int{{$}}
static let staticVar2 = 42
// FIXME: PRINTED_WITHOUT_TYPE
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue static let staticVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue static let staticVar2: Int{{$}}
}
struct d0200_EscapedIdentifiers {
// PASS_COMMON-LABEL: {{^}}struct d0200_EscapedIdentifiers {{{$}}
struct `struct` {}
// PASS_COMMON-NEXT: {{^}} struct `struct` {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum `enum` {
case `case`
}
// PASS_COMMON-NEXT: {{^}} enum `enum` {{{$}}
// PASS_COMMON-NEXT: {{^}} case `case`{{$}}
// PASS_COMMON-NEXT: {{^}} {{.*}}static func __derived_enum_equals(_ a: d0200_EscapedIdentifiers.`enum`, _ b: d0200_EscapedIdentifiers.`enum`) -> Bool
// PASS_COMMON-NEXT: {{^}} func hash(into hasher: inout Hasher)
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class `class` {}
// PASS_COMMON-NEXT: {{^}} class `class` {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
typealias `protocol` = `class`
// PASS_ONE_LINE_TYPE-DAG: {{^}} typealias `protocol` = d0200_EscapedIdentifiers.`class`{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} typealias `protocol` = `class`{{$}}
class `extension` : `class` {}
// PASS_ONE_LINE_TYPE-DAG: {{^}} @_inheritsConvenienceInitializers class `extension` : d0200_EscapedIdentifiers.`class` {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} @_inheritsConvenienceInitializers class `extension` : `class` {{{$}}
// PASS_COMMON: {{^}} {{(override )?}}init(){{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
func `func`<`let`: `protocol`, `where`>(
class: Int, struct: `protocol`, foo: `let`, bar: `where`) where `where` : `protocol` {}
// PASS_COMMON-NEXT: {{^}} func `func`<`let`, `where`>(class: Int, struct: {{(d0200_EscapedIdentifiers.)?}}`protocol`, foo: `let`, bar: `where`) where `let` : {{(d0200_EscapedIdentifiers.)?}}`class`, `where` : {{(d0200_EscapedIdentifiers.)?}}`class`{{$}}
var `var`: `struct` = `struct`()
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue var `var`: {{(d0200_EscapedIdentifiers.)?}}`struct`{{$}}
var tupleType: (`var`: Int, `let`: `struct`)
// PASS_COMMON-NEXT: {{^}} var tupleType: (var: Int, let: {{(d0200_EscapedIdentifiers.)?}}`struct`){{$}}
var accessors1: Int {
get { return 0 }
set(`let`) {}
}
// PASS_COMMON-NEXT: {{^}} var accessors1: Int{{( { get set })?}}{{$}}
static func `static`(protocol: Int) {}
// PASS_COMMON-NEXT: {{^}} static func `static`(protocol: Int){{$}}
// PASS_COMMON-NEXT: {{^}} init(var: {{(d0200_EscapedIdentifiers.)?}}`struct` = {{(d0200_EscapedIdentifiers.)?}}`struct`(), tupleType: (var: Int, let: {{(d0200_EscapedIdentifiers.)?}}`struct`)){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
}
struct d0210_Qualifications {
// PASS_QUAL_UNQUAL: {{^}}struct d0210_Qualifications {{{$}}
// PASS_QUAL_IF_AMBIGUOUS: {{^}}struct d0210_Qualifications {{{$}}
var propFromStdlib1: Int = 0
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromStdlib1: Int{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromStdlib1: Int{{$}}
var propFromSwift1: FooSwiftStruct = FooSwiftStruct()
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromSwift1: FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromSwift1: foo_swift_module.FooSwiftStruct{{$}}
var propFromClang1: FooStruct1 = FooStruct1(x: 0, y: 0.0)
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromClang1: FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromClang1: FooStruct1{{$}}
func instanceFuncFromStdlib1(a: Int) -> Float {
return 0.0
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}}
func instanceFuncFromStdlib2(a: ObjCBool) {}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}}
func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct {
return FooSwiftStruct()
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromSwift1(a: foo_swift_module.FooSwiftStruct) -> foo_swift_module.FooSwiftStruct{{$}}
func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1 {
return FooStruct1(x: 0, y: 0.0)
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}}
}
// FIXME: this should be printed reasonably in case we use
// -prefer-type-repr=true. Either we should print the types we inferred, or we
// should print the initializers.
class d0250_ExplodePattern {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0250_ExplodePattern {{{$}}
var instanceVar1 = 0
var instanceVar2 = 0.0
var instanceVar3 = ""
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar3: String{{$}}
var instanceVar4 = FooStruct()
var (instanceVar5, instanceVar6) = (FooStruct(), FooStruct())
var (instanceVar7, instanceVar8) = (FooStruct(), FooStruct())
var (instanceVar9, instanceVar10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct())
final var (instanceVar11, instanceVar12) = (FooStruct(), FooStruct())
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar10: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final var instanceVar11: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final var instanceVar12: FooStruct{{$}}
let instanceLet1 = 0
let instanceLet2 = 0.0
let instanceLet3 = ""
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet3: String{{$}}
let instanceLet4 = FooStruct()
let (instanceLet5, instanceLet6) = (FooStruct(), FooStruct())
let (instanceLet7, instanceLet8) = (FooStruct(), FooStruct())
let (instanceLet9, instanceLet10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct())
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet10: FooStruct{{$}}
}
class d0260_ExplodePattern_TestClassBase {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0260_ExplodePattern_TestClassBase {{{$}}
init() {
baseProp1 = 0
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} init(){{$}}
final var baseProp1: Int
// PASS_EXPLODE_PATTERN-NEXT: {{^}} final var baseProp1: Int{{$}}
var baseProp2: Int {
get {
return 0
}
set {}
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} var baseProp2: Int{{$}}
}
class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}@_inheritsConvenienceInitializers class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {{{$}}
override final var baseProp2: Int {
get {
return 0
}
set {}
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} override final var baseProp2: Int{{$}}
}
//===---
//===--- Inheritance list in structs.
//===---
struct StructWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithoutInheritance1 {{{$}}
struct StructWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance1 : FooProtocol {{{$}}
struct StructWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance2 : FooProtocol, BarProtocol {{{$}}
struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in classes.
//===---
class ClassWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithoutInheritance1 {{{$}}
class ClassWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance1 : FooProtocol {{{$}}
class ClassWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance2 : FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance3 : FooClass {}
// PASS_ONE_LINE-DAG: {{^}}@_inheritsConvenienceInitializers class ClassWithInheritance3 : FooClass {{{$}}
class ClassWithInheritance4 : FooClass, FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}@_inheritsConvenienceInitializers class ClassWithInheritance4 : FooClass, FooProtocol {{{$}}
class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}@_inheritsConvenienceInitializers class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in enums.
//===---
enum EnumWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithoutInheritance1 {{{$}}
enum EnumWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance1 : FooProtocol {{{$}}
enum EnumWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance2 : FooProtocol, BarProtocol {{{$}}
enum EnumDeclWithUnderlyingType1 : Int { case X }
// PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType1 : Int {{{$}}
enum EnumDeclWithUnderlyingType2 : Int, FooProtocol { case X }
// PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType2 : Int, FooProtocol {{{$}}
enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in protocols.
//===---
protocol ProtocolWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithoutInheritance1 {{{$}}
protocol ProtocolWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance1 : FooProtocol {{{$}}
protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol { }
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance2 : BarProtocol, FooProtocol {{{$}}
protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {
}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in extensions
//===---
struct StructInherited { }
// PASS_ONE_LINE-DAG: {{.*}}extension StructInherited : QuxProtocol, SubFooProtocol {{{$}}
extension StructInherited : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
//===---
//===--- Typealias printing.
//===---
// Normal typealiases.
typealias SimpleTypealias1 = FooProtocol
// PASS_ONE_LINE-DAG: {{^}}typealias SimpleTypealias1 = FooProtocol{{$}}
// Associated types.
protocol AssociatedType1 {
associatedtype AssociatedTypeDecl1 = Int
// PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl1 = Int{{$}}
associatedtype AssociatedTypeDecl2 : FooProtocol
// PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl2 : FooProtocol{{$}}
associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl3 : BarProtocol, FooProtocol{{$}}
associatedtype AssociatedTypeDecl4 where AssociatedTypeDecl4 : QuxProtocol, AssociatedTypeDecl4.Qux == Int
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl4 : QuxProtocol where Self.AssociatedTypeDecl4.Qux == Int{{$}}
associatedtype AssociatedTypeDecl5: FooClass
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl5 : FooClass{{$}}
}
//===---
//===--- Variable declaration printing.
//===---
var d0300_topLevelVar1: Int = 42
// PASS_COMMON: {{^}}@_hasInitialValue var d0300_topLevelVar1: Int{{$}}
// PASS_COMMON-NOT: d0300_topLevelVar1
var d0400_topLevelVar2: Int = 42
// PASS_COMMON: {{^}}@_hasInitialValue var d0400_topLevelVar2: Int{{$}}
// PASS_COMMON-NOT: d0400_topLevelVar2
var d0500_topLevelVar2: Int {
get {
return 42
}
}
// PASS_COMMON: {{^}}var d0500_topLevelVar2: Int { get }{{$}}
// PASS_COMMON-NOT: d0500_topLevelVar2
class d0600_InClassVar1 {
// PASS_O600-LABEL: d0600_InClassVar1
var instanceVar1: Int
// PASS_COMMON: {{^}} var instanceVar1: Int{{$}}
// PASS_COMMON-NOT: instanceVar1
var instanceVar2: Int = 42
// PASS_COMMON: {{^}} @_hasInitialValue var instanceVar2: Int{{$}}
// PASS_COMMON-NOT: instanceVar2
// FIXME: this is sometimes printed without a type, see PASS_EXPLODE_PATTERN.
// FIXME: PRINTED_WITHOUT_TYPE
var instanceVar3 = 42
// PASS_COMMON: {{^}} @_hasInitialValue var instanceVar3
// PASS_COMMON-NOT: instanceVar3
var instanceVar4: Int {
get {
return 42
}
}
// PASS_COMMON: {{^}} var instanceVar4: Int { get }{{$}}
// PASS_COMMON-NOT: instanceVar4
static var staticVar1: Int = 42
// PASS_COMMON: {{^}} @_hasInitialValue static var staticVar1: Int{{$}}
// PASS_COMMON-NOT: staticVar1
static var staticVar2: Int { 42 }
// PASS_COMMON: {{^}} static var staticVar2: Int { get }{{$}}
// PASS_COMMON-NOT: staticVar2
init() {
instanceVar1 = 10
}
}
//===---
//===--- Subscript declaration printing.
//===---
class d0700_InClassSubscript1 {
// PASS_COMMON-LABEL: d0700_InClassSubscript1
subscript(i: Int) -> Int {
get {
return 42
}
}
subscript(index i: Float) -> Int { return 42 }
class `class` {}
subscript(x: Float) -> `class` { return `class`() }
// PASS_COMMON: {{^}} subscript(i: Int) -> Int { get }{{$}}
// PASS_COMMON: {{^}} subscript(index i: Float) -> Int { get }{{$}}
// PASS_COMMON: {{^}} subscript(x: Float) -> {{.*}} { get }{{$}}
// PASS_COMMON-NOT: subscript
// PASS_ONE_LINE_TYPE: {{^}} subscript(x: Float) -> d0700_InClassSubscript1.`class` { get }{{$}}
// PASS_ONE_LINE_TYPEREPR: {{^}} subscript(x: Float) -> `class` { get }{{$}}
}
// PASS_COMMON: {{^}}}{{$}}
//===---
//===--- Constructor declaration printing.
//===---
struct d0800_ExplicitConstructors1 {
// PASS_COMMON-LABEL: d0800_ExplicitConstructors1
init() {}
// PASS_COMMON: {{^}} init(){{$}}
init(a: Int) {}
// PASS_COMMON: {{^}} init(a: Int){{$}}
}
struct d0900_ExplicitConstructorsSelector1 {
// PASS_COMMON-LABEL: d0900_ExplicitConstructorsSelector1
init(int a: Int) {}
// PASS_COMMON: {{^}} init(int a: Int){{$}}
init(int a: Int, andFloat b: Float) {}
// PASS_COMMON: {{^}} init(int a: Int, andFloat b: Float){{$}}
}
struct d1000_ExplicitConstructorsSelector2 {
// PASS_COMMON-LABEL: d1000_ExplicitConstructorsSelector2
init(noArgs _: ()) {}
// PASS_COMMON: {{^}} init(noArgs _: ()){{$}}
init(_ a: Int) {}
// PASS_COMMON: {{^}} init(_ a: Int){{$}}
init(_ a: Int, withFloat b: Float) {}
// PASS_COMMON: {{^}} init(_ a: Int, withFloat b: Float){{$}}
init(int a: Int, _ b: Float) {}
// PASS_COMMON: {{^}} init(int a: Int, _ b: Float){{$}}
}
//===---
//===--- Destructor declaration printing.
//===---
class d1100_ExplicitDestructor1 {
// PASS_COMMON-LABEL: d1100_ExplicitDestructor1
deinit {}
// PASS_COMMON: {{^}} @objc deinit{{$}}
}
//===---
//===--- Enum declaration printing.
//===---
enum d2000_EnumDecl1 {
case ED1_First
case ED1_Second
}
// PASS_COMMON: {{^}}enum d2000_EnumDecl1 {{{$}}
// PASS_COMMON-NEXT: {{^}} case ED1_First{{$}}
// PASS_COMMON-NEXT: {{^}} case ED1_Second{{$}}
// PASS_COMMON-NEXT: {{^}} {{.*}}static func __derived_enum_equals(_ a: d2000_EnumDecl1, _ b: d2000_EnumDecl1) -> Bool
// PASS_COMMON-NEXT: {{^}} func hash(into hasher: inout Hasher)
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2100_EnumDecl2 {
case ED2_A(Int)
case ED2_B(Float)
case ED2_C(Int, Float)
case ED2_D(x: Int, y: Float)
case ED2_E(x: Int, y: (Float, Double))
case ED2_F(x: Int, (y: Float, z: Double))
}
// PASS_COMMON: {{^}}enum d2100_EnumDecl2 {{{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_A(Int){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_B(Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_C(Int, Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_D(x: Int, y: Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_E(x: Int, y: (Float, Double)){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_F(x: Int, (y: Float, z: Double)){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2200_EnumDecl3 {
case ED3_A, ED3_B
case ED3_C(Int), ED3_D
case ED3_E, ED3_F(Int)
case ED3_G(Int), ED3_H(Int)
case ED3_I(Int), ED3_J(Int), ED3_K
}
// PASS_2200: {{^}}enum d2200_EnumDecl3 {{{$}}
// PASS_2200-NEXT: {{^}} case ED3_A, ED3_B{{$}}
// PASS_2200-NEXT: {{^}} case ED3_C(Int), ED3_D{{$}}
// PASS_2200-NEXT: {{^}} case ED3_E, ED3_F(Int){{$}}
// PASS_2200-NEXT: {{^}} case ED3_G(Int), ED3_H(Int){{$}}
// PASS_2200-NEXT: {{^}} case ED3_I(Int), ED3_J(Int), ED3_K{{$}}
// PASS_2200-NEXT: {{^}}}{{$}}
// PASS_2200_DESERIALIZED: {{^}}enum d2200_EnumDecl3 {{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_A{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_B{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_C(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_D{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_E{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_F(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_G(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_H(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_I(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_J(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_K{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}}}{{$}}
enum d2300_EnumDeclWithValues1 : Int {
case EDV2_First = 10
case EDV2_Second
}
// PASS_COMMON: {{^}}enum d2300_EnumDeclWithValues1 : Int {{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV2_First{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV2_Second{{$}}
// PASS_COMMON-DAG: {{^}} typealias RawValue = Int
// PASS_COMMON-DAG: {{^}} init?(rawValue: Int){{$}}
// PASS_COMMON-DAG: {{^}} var rawValue: Int { get }{{$}}
// PASS_COMMON: {{^}}}{{$}}
enum d2400_EnumDeclWithValues2 : Double {
case EDV3_First = 10
case EDV3_Second
}
// PASS_COMMON: {{^}}enum d2400_EnumDeclWithValues2 : Double {{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV3_First{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV3_Second{{$}}
// PASS_COMMON-DAG: {{^}} typealias RawValue = Double
// PASS_COMMON-DAG: {{^}} init?(rawValue: Double){{$}}
// PASS_COMMON-DAG: {{^}} var rawValue: Double { get }{{$}}
// PASS_COMMON: {{^}}}{{$}}
//===---
//===--- Custom operator printing.
//===---
postfix operator <*>
// PASS_2500-LABEL: {{^}}postfix operator <*>{{$}}
protocol d2600_ProtocolWithOperator1 {
static postfix func <*>(_: Self)
}
// PASS_2500: {{^}}protocol d2600_ProtocolWithOperator1 {{{$}}
// PASS_2500-NEXT: {{^}} postfix static func <*> (_: Self){{$}}
// PASS_2500-NEXT: {{^}}}{{$}}
struct d2601_TestAssignment {}
infix operator %%%
func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int {
return 0
}
// PASS_2500-LABEL: {{^}}infix operator %%% : DefaultPrecedence{{$}}
// PASS_2500: {{^}}func %%% (lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int{{$}}
precedencegroup BoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringPrecedence {{{$}}
associativity: left
// PASS_2500-NEXT: {{^}} associativity: left{{$}}
higherThan: AssignmentPrecedence
// PASS_2500-NEXT: {{^}} higherThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: assignment
// PASS_2500-NOT: lowerThan
}
precedencegroup ReallyBoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup ReallyBoringPrecedence {{{$}}
associativity: right
// PASS_2500-NEXT: {{^}} associativity: right{{$}}
// PASS_2500-NOT: higherThan
// PASS_2500-NOT: lowerThan
// PASS_2500-NOT: assignment
}
precedencegroup BoringAssignmentPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringAssignmentPrecedence {{{$}}
lowerThan: AssignmentPrecedence
assignment: true
// PASS_2500-NEXT: {{^}} assignment: true{{$}}
// PASS_2500-NEXT: {{^}} lowerThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: associativity
// PASS_2500-NOT: higherThan
}
// PASS_2500: {{^}}}{{$}}
//===---
//===--- Printing of deduced associated types.
//===---
protocol d2700_ProtocolWithAssociatedType1 {
associatedtype TA1
func returnsTA1() -> TA1
}
// PREFER_TYPE_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} func returnsTA1() -> Self.TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}}}{{$}}
// PREFER_TYPEREPR_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} func returnsTA1() -> TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}}}{{$}}
struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {
func returnsTA1() -> Int {
return 42
}
}
// PASS_COMMON: {{^}}struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {{{$}}
// PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Int{{$}}
// PASS_COMMON-NEXT: {{^}} typealias TA1 = Int
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
//===---
//===--- Generic parameter list printing.
//===---
struct GenericParams1<
StructGenericFoo : FooProtocol,
StructGenericFooX : FooClass,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
// PASS_ONE_LINE_TYPE-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
init<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
func genericParams1<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
func contextualWhereClause1() where StructGenericBaz == Never {}
// PASS_PRINT_AST: func contextualWhereClause1() where StructGenericBaz == Never{{$}}
subscript(index: Int) -> Never where StructGenericBaz: FooProtocol {
return fatalError()
}
// PASS_PRINT_AST: subscript(index: Int) -> Never where StructGenericBaz : FooProtocol { get }{{$}}
}
extension GenericParams1 where StructGenericBaz: FooProtocol {
static func contextualWhereClause2() where StructGenericBaz: FooClass {}
// PASS_PRINT_AST: static func contextualWhereClause2() where StructGenericBaz : FooClass{{$}}
typealias ContextualWhereClause3 = Never where StructGenericBaz: QuxProtocol, StructGenericBaz.Qux == Void
// PASS_PRINT_AST: typealias ContextualWhereClause3 = Never where StructGenericBaz : QuxProtocol, StructGenericBaz.Qux == (){{$}}
}
struct GenericParams2<T : FooProtocol> where T : BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams2<T> where T : BarProtocol, T : FooProtocol {{{$}}
struct GenericParams3<T : FooProtocol> where T : BarProtocol, T : QuxProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams3<T> where T : BarProtocol, T : FooProtocol, T : QuxProtocol {{{$}}
struct GenericParams4<T : QuxProtocol> where T.Qux : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams4<T> where T : QuxProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams5<T : QuxProtocol> where T.Qux : FooProtocol & BarProtocol {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams6<T : QuxProtocol, U : QuxProtocol> where T.Qux == U.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
struct GenericParams7<T : QuxProtocol, U : QuxProtocol> where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
//===---
//===--- Tupe sugar for library types.
//===---
struct d2900_TypeSugar1 {
// PASS_COMMON-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}}
func f1(x: [Int]) {}
// PASS_COMMON-NEXT: {{^}} func f1(x: [Int]){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f1(x: [Int]){{$}}
func f2(x: Array<Int>) {}
// PASS_COMMON-NEXT: {{^}} func f2(x: Array<Int>){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f2(x: [Int]){{$}}
func f3(x: Int?) {}
// PASS_COMMON-NEXT: {{^}} func f3(x: Int?){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f3(x: Int?){{$}}
func f4(x: Optional<Int>) {}
// PASS_COMMON-NEXT: {{^}} func f4(x: Optional<Int>){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f4(x: Int?){{$}}
func f5(x: [Int]...) {}
// PASS_COMMON-NEXT: {{^}} func f5(x: [Int]...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f5(x: [Int]...){{$}}
func f6(x: Array<Int>...) {}
// PASS_COMMON-NEXT: {{^}} func f6(x: Array<Int>...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f6(x: [Int]...){{$}}
func f7(x: [Int : Int]...) {}
// PASS_COMMON-NEXT: {{^}} func f7(x: [Int : Int]...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f7(x: [Int : Int]...){{$}}
func f8(x: Dictionary<String, Int>...) {}
// PASS_COMMON-NEXT: {{^}} func f8(x: Dictionary<String, Int>...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f8(x: [String : Int]...){{$}}
}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
// @discardableResult attribute
public struct DiscardableThingy {
// PASS_PRINT_AST: @discardableResult
// PASS_PRINT_AST-NEXT: public init()
@discardableResult
public init() {}
// PASS_PRINT_AST: @discardableResult
// PASS_PRINT_AST-NEXT: public func useless() -> Int
@discardableResult
public func useless() -> Int { return 0 }
}
// Parameter Attributes.
// <rdar://problem/19775868> Swift 1.2b1: Header gen puts @autoclosure in the wrong place
// PASS_PRINT_AST: public func ParamAttrs1(a: @autoclosure () -> ())
public func ParamAttrs1(a : @autoclosure () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs2(a: @autoclosure @escaping () -> ())
public func ParamAttrs2(a : @autoclosure @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs3(a: () -> ())
public func ParamAttrs3(a : () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs4(a: @escaping () -> ())
public func ParamAttrs4(a : @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs5(a: (@escaping () -> ()) -> ())
public func ParamAttrs5(a : (@escaping () -> ()) -> ()) {
}
// PASS_PRINT_AST: public typealias ParamAttrs6 = (@autoclosure () -> ()) -> ()
public typealias ParamAttrs6 = (@autoclosure () -> ()) -> ()
// The following type only has the internal paramter name inferred from the
// closure on the right-hand side of `=`. Thus, it is only part of the `Type`
// and not part of the `TypeRepr`.
// PASS_PRINT_AST_TYPE: public var ParamAttrs7: (_ f: @escaping () -> ()) -> ()
// PASS_PRINT_AST_TYPEREPR: public var ParamAttrs7: (@escaping () -> ()) -> ()
public var ParamAttrs7: (@escaping () -> ()) -> () = { f in f() }
// PASS_PRINT_AST: public var ParamAttrs8: (_ f: @escaping () -> ()) -> ()
public var ParamAttrs8: (_ f: @escaping () -> ()) -> () = { f in f() }
// Setter
// PASS_PRINT_AST: class FooClassComputed {
class FooClassComputed {
// PASS_PRINT_AST: var stored: (((Int) -> Int) -> Int)?
var stored : (((Int) -> Int) -> Int)? = nil
// PASS_PRINT_AST: var computed: ((Int) -> Int) -> Int { get set }
var computed : ((Int) -> Int) -> Int {
get { return stored! }
set { stored = newValue }
}
// PASS_PRINT_AST: }
}
// PASS_PRINT_AST: struct HasDefaultTupleOfNils {
// PASS_PRINT_AST: var x: (Int?, Int?)
// PASS_PRINT_AST: var y: Int?
// PASS_PRINT_AST: var z: Int
// PASS_PRINT_AST: var w: ((Int?, (), Int?), (Int?, Int?))
// PASS_PRINT_AST: init(x: (Int?, Int?) = (nil, nil), y: Int? = nil, z: Int, w: ((Int?, (), Int?), (Int?, Int?)) = ((nil, (), nil), (nil, nil)))
// PASS_PRINT_AST: }
struct HasDefaultTupleOfNils {
var x: (Int?, Int?)
var y: Int?
var z: Int
var w: ((Int?, (), Int?), (Int?, Int?))
}
// Protocol extensions
protocol ProtocolToExtend {
associatedtype Assoc
}
extension ProtocolToExtend where Self.Assoc == Int {}
// PREFER_TYPE_REPR_PRINTING: extension ProtocolToExtend where Self.Assoc == Int {
// Protocol with where clauses
protocol ProtocolWithWhereClause : QuxProtocol where Qux == Int {}
// PREFER_TYPE_REPR_PRINTING: protocol ProtocolWithWhereClause : QuxProtocol where Self.Qux == Int {
protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Qux == Int {
// PREFER_TYPE_REPR_PRINTING-DAG: protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Self.Qux == Int {
associatedtype A1 : QuxProtocol where A1 : FooProtocol, A1.Qux : QuxProtocol, Int == A1.Qux.Qux
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A1 : FooProtocol, QuxProtocol where Self.A1.Qux : QuxProtocol, Self.A1.Qux.Qux == Int{{$}}
associatedtype A2 : QuxProtocol where A2.Qux == Self
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A2 : QuxProtocol where Self == Self.A2.Qux{{$}}
}
#if true
#elseif false
#else
#endif
// PASS_PRINT_AST: #if
// PASS_PRINT_AST: #elseif
// PASS_PRINT_AST: #else
// PASS_PRINT_AST: #endif
public struct MyPair<A, B> { var a: A, b: B }
public typealias MyPairI<B> = MyPair<Int, B>
// PASS_PRINT_AST: public typealias MyPairI<B> = MyPair<Int, B>
public typealias MyPairAlias<T, U> = MyPair<T, U>
// PASS_PRINT_AST: public typealias MyPairAlias<T, U> = MyPair<T, U>
typealias MyPairAlias2<T: FooProtocol, U> = MyPair<T, U> where U: BarProtocol
// PASS_PRINT_AST: typealias MyPairAlias2<T, U> = MyPair<T, U> where T : FooProtocol, U : BarProtocol
|
apache-2.0
|
8034c0c4c31363f4ab6b6beaea2a5543
| 39.004861 | 385 | 0.650598 | 3.702011 | false | false | false | false |
Crebs/Discrete-Mathematics
|
DiscreteMathProblems/DiscreteMathProblems/Matrix.swift
|
1
|
2502
|
//
// Matrix.swift
// DiscreteMathProblems
//
// Created by Riley Crebs on 3/15/16.
// Copyright © 2016 Incravo. All rights reserved.
//
import Foundation
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
/**
*/
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0.0)
}
/**
*/
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
/**
*/
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
// MARK
/**
Algorithm for Zero-one matrix, the boolean product. See Rosen page 253
Section 3.8
@param left Matrix perform operation on.
@param right Matrix
@return Boolean product
*/
static func zeroOneProduct(left: Matrix, right: Matrix) -> Matrix {
return Matrix.matrixProduct(left, right: right, procedure: { Double(Int($0) | (Int($1) & Int($2)))})
}
/**
Helper method used for looping through matrices to produce product.
@param left Matrix peform operation on.
@param right Matrix
@param Closure to handle procedure.
*/
static func matrixProduct(left: Matrix, right:Matrix, procedure:(Double, Double, Double) -> Double) -> Matrix {
var resultMatrix = Matrix(rows: left.rows, columns: right.columns)
for i in 0...left.rows - 1 {
for j in 0...right.columns - 1 {
resultMatrix[i,j] = 0
for q in 0...left.columns - 1 {
resultMatrix[i, j] = procedure(resultMatrix[i,j], left[i,q], right[q,j])
}
}
}
return resultMatrix
}
}
/**
Algorithm for Matrix Multiplication. O(n^3) See Rosen page 249 Section 3.8
@param left Matrix to left of muliplication operator.
@param right Matrix to right of muliplication operator.
@return New matrix from multiplication of left and right matrices.
*/
func * (left: Matrix, right:Matrix) -> Matrix {
return Matrix.matrixProduct(left, right: right, procedure: {$0 + ($1 * $2)})
}
|
mit
|
1aba05b05b86fb7b7a8599e16e320403
| 30.2625 | 115 | 0.588165 | 3.988836 | false | false | false | false |
manfengjun/KYMart
|
Section/LogAndReg/View/KYCodeView.swift
|
1
|
3298
|
//
// KYCodeView.swift
// KYMart
//
// Created by jun on 2017/6/10.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYCodeView: UIView {
var textColor:UIColor = UIColor.black
var textSize:CGFloat = 0
var changeString:String!
var characters:[String]!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
change()
}
init(frame:CGRect, characterArray:[String]) {
super.init(frame: frame)
backgroundColor = UIColor.randomColor(alpha: 0.2)
characters = characterArray
}
func refresh() {
changeCode()
}
func changeCode() {
change()
setNeedsDisplay()
}
func setup() {
let tap = UITapGestureRecognizer(target: self, action: #selector(refresh))
addGestureRecognizer(tap)
}
func change() {
if characters == nil || characters.isEmpty {
characters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
}
changeString = ""
for _ in 0..<4 {
let index = Int(arc4random())%(characters.count - 1)
let resultStr = characters[index]
changeString.append(resultStr)
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
var color = UIColor.randomColor(alpha: 0.5)
backgroundColor = color
let text = NSString(string: changeString)
let size = NSString(string: "S").size(attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: textSize>0 ? textSize : 20),NSForegroundColorAttributeName:textColor])
let width = rect.size.width / (CGFloat(text.length) - size.width)
let height = rect.size.height - size.height
var point:CGPoint!
var pX = 0
var pY = 0
for i in 0..<text.length {
pX = Int(arc4random()) % Int(width) + Int(rect.size.width) / text.length*i
pY = Int(arc4random()) % Int(height)
point = CGPoint(x: pX, y: pY)
let c = text.character(at: i)
let textC = NSString(characters: [c], length: 1)
textC.draw(at: point, withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: textSize>0 ? textSize : 20),NSForegroundColorAttributeName:textColor])
}
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(1.0)
for _ in 0..<10 {
color = UIColor.randomColor(alpha: 0.5)
context?.setStrokeColor(color.cgColor)
pX = Int(arc4random()) % Int(rect.size.width);
pY = Int(arc4random()) % Int(rect.size.height);
context?.move(to: CGPoint(x: pX, y: pY))
pX = Int(arc4random()) % Int(rect.size.width);
pY = Int(arc4random()) % Int(rect.size.height);
context?.addLine(to: CGPoint(x: pX, y: pY))
context?.strokePath()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
395f21c840818caf06aeed84f7603fa0
| 36.022472 | 335 | 0.545675 | 3.550647 | false | false | false | false |
diejmon/SwiftyImageIO
|
Sources/ImageDestination.swift
|
1
|
2797
|
import Foundation
import ImageIO
//TODO: Copy/Paste documentation from ImageIO
public final class ImageDestination {
let imageDestination: CGImageDestination
public init?(data: NSMutableData, UTI: UTITypeConvertible, imageCount: Int) {
guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, UTI.UTI.cfType, imageCount, nil)
else { return nil }
self.imageDestination = imageDestination
}
public init?(url: URL, UTI: UTITypeConvertible, imageCount: Int) {
guard let imageDestination = CGImageDestinationCreateWithURL(url as CFURL, UTI.UTI.cfType, imageCount, nil)
else { return nil }
self.imageDestination = imageDestination
}
public init?(dataConsumer: CGDataConsumer, imageType: UTITypeConvertible, imageCount: Int, options: Properties? = nil) {
guard let imageDestination = CGImageDestinationCreateWithDataConsumer(dataConsumer, imageType.UTI.cfType, imageCount, options?.rawCFValues())
else { return nil }
self.imageDestination = imageDestination
}
public struct Properties {
public init() {}
public var lossyCompressionQuality: Double?
public var backgroundColor: CGColor?
public var imageProperties: [ImageProperties]?
}
}
// MARK: - Adding Images
public extension ImageDestination {
func addImage(_ image: CGImage, properties: Properties? = nil) {
CGImageDestinationAddImage(imageDestination, image, properties?.rawCFValues())
}
func addImage(from source: ImageSource, sourceImageIndex: Int, properties: Properties? = nil) {
CGImageDestinationAddImageFromSource(imageDestination, source.imageSource, sourceImageIndex, properties?.rawCFValues())
}
}
// MARK: - Getting Type Identifiers
public extension ImageDestination {
static func supportedUTIs() -> [SwiftyImageIO.UTI] {
return CGImageDestinationCopyTypeIdentifiers().convertToUTIs()
}
static func supportsUTI(_ UTI: UTITypeConvertible) -> Bool {
return supportedUTIs().contains(UTI.UTI)
}
static var typeID: CFTypeID {
return CGImageDestinationGetTypeID()
}
}
// MARK: - Settings Properties
public extension ImageDestination {
func setProperties(_ properties: Properties?) {
CGImageDestinationSetProperties(imageDestination, properties?.rawCFValues())
}
}
// MARK: - Finalizing an Image Destination
public extension ImageDestination {
func finalize() -> Bool {
return CGImageDestinationFinalize(imageDestination)
}
}
extension ImageDestination.Properties: CFValuesRepresentable {
public var cfValues: CFValues {
var result: CFValues = [
kCGImageDestinationLossyCompressionQuality: lossyCompressionQuality,
kCGImageDestinationBackgroundColor: backgroundColor,
]
imageProperties?.merge(into: &result)
return result
}
}
|
mit
|
f5e50963265627dc41c5b5627c249680
| 31.905882 | 145 | 0.75438 | 4.805842 | false | false | false | false |
apple/swift-corelibs-foundation
|
Sources/Foundation/NSPathUtilities.swift
|
1
|
32190
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_implementationOnly import CoreFoundation
#if os(Windows)
let validPathSeps: [Character] = ["\\", "/"]
#else
let validPathSeps: [Character] = ["/"]
#endif
public func NSTemporaryDirectory() -> String {
func normalizedPath(with path: String) -> String {
if validPathSeps.contains(where: { path.hasSuffix(String($0)) }) {
return path
} else {
return path + String(validPathSeps.last!)
}
}
#if os(Windows)
let cchLength: DWORD = GetTempPathW(0, nil)
var wszPath: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(cchLength + 1))
guard GetTempPathW(DWORD(wszPath.count), &wszPath) <= cchLength else {
preconditionFailure("GetTempPathW mutation race")
}
return normalizedPath(with: String(decodingCString: wszPath, as: UTF16.self).standardizingPath)
#else
#if canImport(Darwin)
let safe_confstr = { (name: Int32, buf: UnsafeMutablePointer<Int8>?, len: Int) -> Int in
// POSIX moment of weird: confstr() is one of those annoying APIs which
// can return zero for both error and non-error conditions, so the only
// way to disambiguate is to put errno in a known state before calling.
errno = 0
let result = confstr(name, buf, len)
// result == 0 is only error if errno is not zero. But, if there was an
// error, bail; all possible errors from confstr() are Very Bad Things.
let err = errno // only read errno once in the failure case.
precondition(result > 0 || err == 0, "Unexpected confstr() error: \(err)")
// This is extreme paranoia and should never happen; this would mean
// confstr() returned < 0, which would only happen for impossibly long
// sizes of value or long-dead versions of the OS.
assert(result >= 0, "confstr() returned impossible result: \(result)")
return result
}
let length: Int = safe_confstr(_CS_DARWIN_USER_TEMP_DIR, nil, 0)
if length > 0 {
var buffer: [Int8] = Array<Int8>(repeating: 0, count: length)
let final_length = safe_confstr(_CS_DARWIN_USER_TEMP_DIR, &buffer, buffer.count)
assert(length == final_length, "Value of _CS_DARWIN_USER_TEMP_DIR changed?")
if length > 0 && length < buffer.count {
return String(cString: buffer, encoding: .utf8)!
}
}
#endif
#if !os(WASI)
if let tmpdir = ProcessInfo.processInfo.environment["TMPDIR"] {
return normalizedPath(with: tmpdir)
}
#endif
#if os(Android)
// Bionic uses /data/local/tmp/ as temporary directory. TMPDIR is rarely
// defined.
return "/data/local/tmp/"
#else
return "/tmp/"
#endif
#endif
}
extension String {
internal var _startOfLastPathComponent : String.Index {
precondition(!validPathSeps.contains(where: { hasSuffix(String($0)) }) && length > 1)
let startPos = startIndex
var curPos = endIndex
// Find the beginning of the component
while curPos > startPos {
let prevPos = index(before: curPos)
if validPathSeps.contains(self[prevPos]) {
break
}
curPos = prevPos
}
return curPos
}
internal var _startOfPathExtension : String.Index? {
precondition(!validPathSeps.contains(where: { hasSuffix(String($0)) }))
var currentPosition = endIndex
let startOfLastPathComponent = _startOfLastPathComponent
// Find the beginning of the extension
while currentPosition > startOfLastPathComponent {
let previousPosition = index(before: currentPosition)
let character = self[previousPosition]
if validPathSeps.contains(character) {
return nil
} else if character == "." {
if startOfLastPathComponent == previousPosition {
return nil
} else if case let previous2Position = index(before: previousPosition),
previousPosition == index(before: endIndex) &&
previous2Position == startOfLastPathComponent &&
self[previous2Position] == "."
{
return nil
} else {
return currentPosition
}
}
currentPosition = previousPosition
}
return nil
}
internal var isAbsolutePath: Bool {
if hasPrefix("~") { return true }
#if os(Windows)
guard let value = try? FileManager.default._fileSystemRepresentation(withPath: self, {
!PathIsRelativeW($0)
}) else { return false }
return value
#else
return hasPrefix("/")
#endif
}
internal func _stringByAppendingPathComponent(_ str: String, doneAppending : Bool = true) -> String {
if str.isEmpty {
return self
}
if isEmpty {
return str
}
if validPathSeps.contains(where: { hasSuffix(String($0)) }) {
return self + str
}
return self + "/" + str
}
internal func _stringByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String {
var result = self
if compress {
let startPos = result.startIndex
var endPos = result.endIndex
var curPos = startPos
while curPos < endPos {
if validPathSeps.contains(result[curPos]) {
var afterLastSlashPos = curPos
while afterLastSlashPos < endPos && validPathSeps.contains(result[afterLastSlashPos]) {
afterLastSlashPos = result.index(after: afterLastSlashPos)
}
if afterLastSlashPos != result.index(after: curPos) {
result.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"])
endPos = result.endIndex
}
curPos = afterLastSlashPos
} else {
curPos = result.index(after: curPos)
}
}
}
if stripTrailing && result.length > 1 && validPathSeps.contains(where: {result.hasSuffix(String($0))}) {
result.remove(at: result.index(before: result.endIndex))
}
return result
}
internal func _stringByRemovingPrefix(_ prefix: String) -> String {
guard hasPrefix(prefix) else {
return self
}
var temp = self
temp.removeSubrange(startIndex..<prefix.endIndex)
return temp
}
#if !os(WASI)
internal func _tryToRemovePathPrefix(_ prefix: String) -> String? {
guard self != prefix else {
return nil
}
let temp = _stringByRemovingPrefix(prefix)
if FileManager.default.fileExists(atPath: temp) {
return temp
}
return nil
}
#endif
}
extension NSString {
public var isAbsolutePath: Bool {
return (self as String).isAbsolutePath
}
public static func path(withComponents components: [String]) -> String {
var result = ""
for comp in components.prefix(components.count - 1) {
result = result._stringByAppendingPathComponent(comp._stringByFixingSlashes(), doneAppending: false)
}
if let last = components.last {
result = result._stringByAppendingPathComponent(last._stringByFixingSlashes(), doneAppending: true)
}
return result
}
public var pathComponents : [String] {
return _pathComponents(self._swiftObject)!
}
public var lastPathComponent : String {
let fixedSelf = _stringByFixingSlashes()
if fixedSelf.length <= 1 {
return fixedSelf
}
return String(fixedSelf.suffix(from: fixedSelf._startOfLastPathComponent))
}
public var deletingLastPathComponent : String {
let fixedSelf = _stringByFixingSlashes()
if fixedSelf == "/" || fixedSelf == "" {
return fixedSelf
}
switch fixedSelf._startOfLastPathComponent {
// relative path, single component
case fixedSelf.startIndex:
return ""
// absolute path, single component
case fixedSelf.index(after: fixedSelf.startIndex):
return "/"
// all common cases
case let startOfLast:
return String(fixedSelf.prefix(upTo: fixedSelf.index(before: startOfLast)))
}
}
internal func _stringByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String {
if validPathSeps.contains(where: { String($0) == _swiftObject }) {
return _swiftObject
}
var result = _swiftObject
if compress {
let startPos = result.startIndex
var endPos = result.endIndex
var curPos = startPos
while curPos < endPos {
if validPathSeps.contains(result[curPos]) {
var afterLastSlashPos = curPos
while afterLastSlashPos < endPos && validPathSeps.contains(result[afterLastSlashPos]) {
afterLastSlashPos = result.index(after: afterLastSlashPos)
}
if afterLastSlashPos != result.index(after: curPos) {
result.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"])
endPos = result.endIndex
}
curPos = afterLastSlashPos
} else {
curPos = result.index(after: curPos)
}
}
}
if stripTrailing && validPathSeps.contains(where: { result.hasSuffix(String($0)) }) {
result.remove(at: result.index(before: result.endIndex))
}
return result
}
internal func _stringByAppendingPathComponent(_ str: String, doneAppending : Bool = true) -> String {
return _swiftObject._stringByAppendingPathComponent(str, doneAppending: doneAppending)
}
public func appendingPathComponent(_ str: String) -> String {
return _stringByAppendingPathComponent(str)
}
public var pathExtension : String {
let fixedSelf = _stringByFixingSlashes()
if fixedSelf.length <= 1 {
return ""
}
if let extensionPos = fixedSelf._startOfPathExtension {
return String(fixedSelf.suffix(from: extensionPos))
} else {
return ""
}
}
public var deletingPathExtension: String {
let fixedSelf = _stringByFixingSlashes()
if fixedSelf.length <= 1 {
return fixedSelf
}
if let extensionPos = fixedSelf._startOfPathExtension {
return String(fixedSelf.prefix(upTo: fixedSelf.index(before: extensionPos)))
} else {
return fixedSelf
}
}
public func appendingPathExtension(_ str: String) -> String? {
if validPathSeps.contains(where: { str.hasPrefix(String($0)) }) || self == "" || validPathSeps.contains(where: { String($0)._nsObject == self }) {
print("Cannot append extension \(str) to path \(self)")
return nil
}
let result = _swiftObject._stringByFixingSlashes(compress: false, stripTrailing: true) + "." + str
return result._stringByFixingSlashes()
}
#if !os(WASI)
public var expandingTildeInPath: String {
guard hasPrefix("~") else {
return _swiftObject
}
let endOfUserName = _swiftObject.firstIndex(where : { validPathSeps.contains($0) }) ?? _swiftObject.endIndex
let startOfUserName = _swiftObject.index(after: _swiftObject.startIndex)
let userName = String(_swiftObject[startOfUserName..<endOfUserName])
let optUserName: String? = userName.isEmpty ? nil : userName
guard let homeDir = NSHomeDirectoryForUser(optUserName) else {
return _swiftObject._stringByFixingSlashes(compress: false, stripTrailing: true)
}
var result = _swiftObject
result.replaceSubrange(_swiftObject.startIndex..<endOfUserName, with: homeDir)
result = result._stringByFixingSlashes(compress: false, stripTrailing: true)
return result
}
#endif
#if os(Windows)
public var unixPath: String {
var unprefixed = self as String
// If there is anything before the drive letter, e.g. "\\?\", "\\host\",
// "\??\", etc, remove it.
if isAbsolutePath, let index = unprefixed.firstIndex(of: ":") {
unprefixed.removeSubrange(..<unprefixed.index(before: index))
}
let converted = String(unprefixed.map({ $0 == "\\" ? "/" : $0 }))
return converted._stringByFixingSlashes(stripTrailing: false)
}
#endif
#if !os(WASI)
public var standardizingPath: String {
#if os(Windows)
let expanded = unixPath.expandingTildeInPath
#else
let expanded = expandingTildeInPath
#endif
var resolved = expanded._bridgeToObjectiveC().resolvingSymlinksInPath
let automount = "/var/automount"
resolved = resolved._tryToRemovePathPrefix(automount) ?? resolved
return resolved
}
public var resolvingSymlinksInPath: String {
var components = pathComponents
guard !components.isEmpty else {
return _swiftObject
}
// TODO: pathComponents keeps final path separator if any. Check that logic.
if validPathSeps.contains(where: { String($0) == components.last }) && components.count > 1 {
components.removeLast()
}
var resolvedPath = components.removeFirst()
for component in components {
switch component {
case "", ".":
break
case ".." where isAbsolutePath:
resolvedPath = resolvedPath._bridgeToObjectiveC().deletingLastPathComponent
default:
resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component)
if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) {
resolvedPath = destination
}
}
}
let privatePrefix = "/private"
resolvedPath = resolvedPath._tryToRemovePathPrefix(privatePrefix) ?? resolvedPath
return resolvedPath
}
#endif
public func stringsByAppendingPaths(_ paths: [String]) -> [String] {
if self == "" {
return paths
}
return paths.map(appendingPathComponent)
}
#if !os(WASI)
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
public func completePath(into outputName: inout String?, caseSensitive flag: Bool, matchesInto outputArray: inout [String], filterTypes: [String]?) -> Int {
let path = _swiftObject
guard !path.isEmpty else {
return 0
}
let url = URL(fileURLWithPath: path)
let searchAllFilesInDirectory = _stringIsPathToDirectory(path)
let namePrefix = searchAllFilesInDirectory ? "" : url.lastPathComponent
let checkFileName = _getFileNamePredicate(namePrefix, caseSensitive: flag)
let checkExtension = _getExtensionPredicate(filterTypes, caseSensitive: flag)
let resolvedURL: URL = url.resolvingSymlinksInPath()
let urlWhereToSearch: URL = searchAllFilesInDirectory ? resolvedURL : resolvedURL.deletingLastPathComponent()
var matches = _getNamesAtURL(urlWhereToSearch, prependWith: "", namePredicate: checkFileName, typePredicate: checkExtension)
if matches.count == 1 {
let theOnlyFoundItem = URL(fileURLWithPath: matches[0], relativeTo: urlWhereToSearch)
if theOnlyFoundItem.hasDirectoryPath {
matches = _getNamesAtURL(theOnlyFoundItem, prependWith: matches[0], namePredicate: nil, typePredicate: checkExtension)
}
}
let commonPath = searchAllFilesInDirectory ? path : _ensureLastPathSeparator(deletingLastPathComponent)
if searchAllFilesInDirectory {
outputName = "/"
} else {
if let lcp = _longestCommonPrefix(matches, caseSensitive: flag) {
outputName = (commonPath + lcp)
}
}
outputArray = matches.map({ (commonPath + $0) })
return matches.count
}
internal func _stringIsPathToDirectory(_ path: String) -> Bool {
if !validPathSeps.contains(where: { path.hasSuffix(String($0)) }) {
return false
}
var isDirectory: ObjCBool = false
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
fileprivate typealias _FileNamePredicate = (String) -> Bool
fileprivate func _getNamesAtURL(_ filePathURL: URL, prependWith: String, namePredicate: _FileNamePredicate?, typePredicate: _FileNamePredicate?) -> [String] {
var result: [String] = []
if let enumerator = FileManager.default.enumerator(at: filePathURL, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants, errorHandler: nil) {
for item in enumerator.lazy.map({ $0 as! URL }) {
let itemName = item.lastPathComponent
if let predicate = namePredicate, !predicate(itemName) { continue }
if let predicate = typePredicate, !predicate(item.pathExtension) { continue }
if prependWith.isEmpty {
result.append(itemName)
} else {
result.append(prependWith._bridgeToObjectiveC().appendingPathComponent(itemName))
}
}
}
return result
}
fileprivate func _getExtensionPredicate(_ extensions: [String]?, caseSensitive: Bool) -> _FileNamePredicate? {
guard let exts = extensions else {
return nil
}
if caseSensitive {
let set = Set(exts)
return { set.contains($0) }
} else {
let set = Set(exts.map { $0.lowercased() })
return {set.contains($0.lowercased()) }
}
}
fileprivate func _getFileNamePredicate(_ prefix: String, caseSensitive: Bool) -> _FileNamePredicate? {
guard !prefix.isEmpty else {
return nil
}
if caseSensitive {
return { $0.hasPrefix(prefix) }
} else {
let prefix = prefix.lowercased()
return { $0.lowercased().hasPrefix(prefix) }
}
}
#endif
internal func _longestCommonPrefix(_ strings: [String], caseSensitive: Bool) -> String? {
guard !strings.isEmpty else {
return nil
}
guard strings.count > 1 else {
return strings.first
}
var sequences = strings.map({ $0.makeIterator() })
var prefix: [Character] = []
loop: while true {
var char: Character? = nil
for (idx, s) in sequences.enumerated() {
var seq = s
guard let c = seq.next() else {
break loop
}
if let char = char {
let lhs = caseSensitive ? char : String(char).lowercased().first!
let rhs = caseSensitive ? c : String(c).lowercased().first!
if lhs != rhs {
break loop
}
} else {
char = c
}
sequences[idx] = seq
}
prefix.append(char!)
}
return String(prefix)
}
internal func _ensureLastPathSeparator(_ path: String) -> String {
if validPathSeps.contains(where: { path.hasSuffix(String($0)) }) || path.isEmpty {
return path
}
return path + "/"
}
#if !os(WASI)
public var fileSystemRepresentation: UnsafePointer<Int8> {
return FileManager.default.fileSystemRepresentation(withPath: self._swiftObject)
}
#endif
public func getFileSystemRepresentation(_ cname: UnsafeMutablePointer<Int8>, maxLength max: Int) -> Bool {
#if os(Windows)
let fsr = UnsafeMutablePointer<WCHAR>.allocate(capacity: max)
defer { fsr.deallocate() }
guard _getFileSystemRepresentation(fsr, maxLength: max) else { return false }
return String(decodingCString: fsr, as: UTF16.self).withCString() {
let chars = strnlen_s($0, max)
guard chars < max else { return false }
cname.assign(from: $0, count: chars + 1)
return true
}
#else
return _getFileSystemRepresentation(cname, maxLength: max)
#endif
}
internal func _getFileSystemRepresentation(_ cname: UnsafeMutablePointer<NativeFSRCharType>, maxLength max: Int) -> Bool {
guard self.length > 0 else {
return false
}
#if os(Windows)
var fsr = self._swiftObject
// If we have a RFC8089 style path, e.g. `/[drive-letter]:/...`, drop
// the leading '/', otherwise, a leading slash indicates a rooted path
// on the drive for the current working directoyr.
if fsr.count >= 3 {
let index0 = fsr.startIndex
let index1 = fsr.index(after: index0)
let index2 = fsr.index(after: index1)
if fsr[index0] == "/" && fsr[index1].isLetter && fsr[index2] == ":" {
fsr.removeFirst()
}
}
// Windows APIs that go through the path parser can handle forward
// slashes in paths. However, symlinks created with forward slashes
// do not resolve properly, so we normalize the path separators anyways.
fsr = fsr.replacingOccurrences(of: "/", with: "\\")
// Drop trailing slashes unless it follows a drive letter. On Windows,
// the path `C:\` indicates the root directory of the `C:` drive. The
// path `C:` indicates the current working directory on the `C:` drive.
while fsr.count > 1 &&
fsr[fsr.index(before: fsr.endIndex)] == "\\" &&
!(fsr.count == 3 &&
fsr[fsr.index(fsr.endIndex, offsetBy: -2)] == ":" &&
fsr[fsr.index(fsr.endIndex, offsetBy: -3)].isLetter) {
fsr.removeLast()
}
return fsr.withCString(encodedAs: UTF16.self) {
let wchars = wcsnlen_s($0, max)
guard wchars < max else { return false }
cname.assign(from: $0, count: wchars + 1)
return true
}
#else
return CFStringGetFileSystemRepresentation(self._cfObject, cname, max)
#endif
}
}
#if !os(WASI)
extension FileManager {
public enum SearchPathDirectory: UInt {
case applicationDirectory // supported applications (Applications)
case demoApplicationDirectory // unsupported applications, demonstration versions (Demos)
case developerApplicationDirectory // developer applications (Developer/Applications). DEPRECATED - there is no one single Developer directory.
case adminApplicationDirectory // system and network administration applications (Administration)
case libraryDirectory // various documentation, support, and configuration files, resources (Library)
case developerDirectory // developer resources (Developer) DEPRECATED - there is no one single Developer directory.
case userDirectory // user home directories (Users)
case documentationDirectory // documentation (Documentation)
case documentDirectory // documents (Documents)
case coreServiceDirectory // location of CoreServices directory (System/Library/CoreServices)
case autosavedInformationDirectory // location of autosaved documents (Documents/Autosaved)
case desktopDirectory // location of user's desktop
case cachesDirectory // location of discardable cache files (Library/Caches)
case applicationSupportDirectory // location of application support files (plug-ins, etc) (Library/Application Support)
case downloadsDirectory // location of the user's "Downloads" directory
case inputMethodsDirectory // input methods (Library/Input Methods)
case moviesDirectory // location of user's Movies directory (~/Movies)
case musicDirectory // location of user's Music directory (~/Music)
case picturesDirectory // location of user's Pictures directory (~/Pictures)
case printerDescriptionDirectory // location of system's PPDs directory (Library/Printers/PPDs)
case sharedPublicDirectory // location of user's Public sharing directory (~/Public)
case preferencePanesDirectory // location of the PreferencePanes directory for use with System Preferences (Library/PreferencePanes)
case applicationScriptsDirectory // location of the user scripts folder for the calling application (~/Library/Application Scripts/code-signing-id)
case itemReplacementDirectory // For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error:
case allApplicationsDirectory // all directories where applications can occur
case allLibrariesDirectory // all directories where resources can occur
case trashDirectory // location of Trash directory
}
public struct SearchPathDomainMask: OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let userDomainMask = SearchPathDomainMask(rawValue: 1) // user's home directory --- place to install user's personal items (~)
public static let localDomainMask = SearchPathDomainMask(rawValue: 2) // local to the current machine --- place to install items available to everyone on this machine (/Library)
public static let networkDomainMask = SearchPathDomainMask(rawValue: 4) // publically available location in the local area network --- place to install items available on the network (/Network)
public static let systemDomainMask = SearchPathDomainMask(rawValue: 8) // provided by Apple, unmodifiable (/System)
public static let allDomainsMask = SearchPathDomainMask(rawValue: 0x0ffff) // all domains: all of the above and future items
}
}
public func NSSearchPathForDirectoriesInDomains(_ directory: FileManager.SearchPathDirectory, _ domainMask: FileManager.SearchPathDomainMask, _ expandTilde: Bool) -> [String] {
let knownDomains: [FileManager.SearchPathDomainMask] = [
.userDomainMask,
.networkDomainMask,
.localDomainMask,
.systemDomainMask,
]
var result: [URL] = []
for domain in knownDomains {
if domainMask.contains(domain) {
result.append(contentsOf: FileManager.default.urls(for: directory, in: domain))
}
}
return result.map { (url) in
var path = url.absoluteURL.path
if expandTilde {
path = NSString(string: path).expandingTildeInPath
}
return path
}
}
public func NSHomeDirectory() -> String {
return NSHomeDirectoryForUser(nil)!
}
public func NSHomeDirectoryForUser(_ user: String?) -> String? {
let userName = user?._cfObject
guard let homeDir = CFCopyHomeDirectoryURLForUser(userName)?.takeRetainedValue() else {
return nil
}
let url: URL = homeDir._swiftObject
return url.path
}
public func NSUserName() -> String {
let userName = CFCopyUserName().takeRetainedValue()
return userName._swiftObject
}
public func NSFullUserName() -> String {
let userName = CFCopyFullUserName()
return userName._swiftObject
}
internal func _NSCreateTemporaryFile(_ filePath: String) throws -> (Int32, String) {
#if os(Windows)
let maxLength: Int = Int(MAX_PATH + 1)
var buf: [UInt16] = Array<UInt16>(repeating: 0, count: maxLength)
let length = GetTempPathW(DWORD(MAX_PATH), &buf)
precondition(length <= MAX_PATH - 14, "temp path too long")
guard "SCF".withCString(encodedAs: UTF16.self, {
return GetTempFileNameW(buf, $0, 0, &buf) != 0
}) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
}
let pathResult = FileManager.default.string(withFileSystemRepresentation: String(decoding: buf, as: UTF16.self), length: wcslen(buf))
guard let h = CreateFileW(buf,
GENERIC_READ | DWORD(GENERIC_WRITE),
DWORD(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE),
nil,
DWORD(OPEN_EXISTING),
DWORD(FILE_ATTRIBUTE_NORMAL),
nil),
h != INVALID_HANDLE_VALUE else {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
}
// Don't close h, fd is transferred ownership
let fd = _open_osfhandle(intptr_t(bitPattern: h), 0)
#else
var template = URL(fileURLWithPath: filePath)
let filename = template.lastPathComponent
let hashed = String(format: "%llx", Int64(filename.hashValue))
template.deleteLastPathComponent()
template.appendPathComponent("SCF.\(hashed).tmp.XXXXXX")
let (fd, errorCode, pathResult) = template.withUnsafeFileSystemRepresentation { ptr -> (Int32, Int32, String) in
let length = strlen(ptr!)
// buffer is updated with the temp file name on success.
let buffer = UnsafeMutableBufferPointer<CChar>.allocate(capacity: length + 1 /* the null character */)
UnsafeRawBufferPointer(start: ptr!, count: length + 1 /* the null character */)
.copyBytes(to: UnsafeMutableRawBufferPointer(buffer))
defer { buffer.deallocate() }
let fd = mkstemp(buffer.baseAddress!)
let errorCode = errno
return (fd,
errorCode,
FileManager.default.string(withFileSystemRepresentation: buffer.baseAddress!, length: strlen(buffer.baseAddress!)))
}
if fd == -1 {
throw _NSErrorWithErrno(errorCode, reading: false, path: pathResult)
}
// Set the file mode to match macOS
guard fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) != -1 else {
let _errno = errno
close(fd)
throw _NSErrorWithErrno(_errno, reading: false, path: pathResult)
}
#endif
return (fd, pathResult)
}
internal func _NSCleanupTemporaryFile(_ auxFilePath: String, _ filePath: String) throws {
try FileManager.default._fileSystemRepresentation(withPath: auxFilePath, andPath: filePath, {
#if os(Windows)
let res = CopyFileW($0, $1, /*bFailIfExists=*/false)
try? FileManager.default.removeItem(atPath: auxFilePath)
if !res {
throw _NSErrorWithWindowsError(GetLastError(), reading: false)
}
#else
if rename($0, $1) != 0 {
let errorCode = errno
try? FileManager.default.removeItem(atPath: auxFilePath)
throw _NSErrorWithErrno(errorCode, reading: false, path: filePath)
}
#endif
})
}
#endif
|
apache-2.0
|
a66b2cddbabd6d26058458049ee15c29
| 37.783133 | 201 | 0.611153 | 4.966826 | false | false | false | false |
WhisperSystems/Signal-iOS
|
SignalServiceKit/src/Devices/OWSLinkedDeviceReadReceipt+SDS.swift
|
1
|
23585
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import GRDB
import SignalCoreKit
// NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py.
// Do not manually edit it, instead run `sds_codegen.sh`.
// MARK: - Record
public struct LinkedDeviceReadReceiptRecord: SDSRecord {
public var tableMetadata: SDSTableMetadata {
return OWSLinkedDeviceReadReceiptSerializer.table
}
public static let databaseTableName: String = OWSLinkedDeviceReadReceiptSerializer.table.tableName
public var id: Int64?
// This defines all of the columns used in the table
// where this model (and any subclasses) are persisted.
public let recordType: SDSRecordType
public let uniqueId: String
// Base class properties
public let linkedDeviceReadReceiptSchemaVersion: UInt
public let messageIdTimestamp: UInt64
public let readTimestamp: UInt64
public let senderPhoneNumber: String?
public let senderUUID: String?
public enum CodingKeys: String, CodingKey, ColumnExpression, CaseIterable {
case id
case recordType
case uniqueId
case linkedDeviceReadReceiptSchemaVersion
case messageIdTimestamp
case readTimestamp
case senderPhoneNumber
case senderUUID
}
public static func columnName(_ column: LinkedDeviceReadReceiptRecord.CodingKeys, fullyQualified: Bool = false) -> String {
return fullyQualified ? "\(databaseTableName).\(column.rawValue)" : column.rawValue
}
}
// MARK: - Row Initializer
public extension LinkedDeviceReadReceiptRecord {
static var databaseSelection: [SQLSelectable] {
return CodingKeys.allCases
}
init(row: Row) {
id = row[0]
recordType = row[1]
uniqueId = row[2]
linkedDeviceReadReceiptSchemaVersion = row[3]
messageIdTimestamp = row[4]
readTimestamp = row[5]
senderPhoneNumber = row[6]
senderUUID = row[7]
}
}
// MARK: - StringInterpolation
public extension String.StringInterpolation {
mutating func appendInterpolation(linkedDeviceReadReceiptColumn column: LinkedDeviceReadReceiptRecord.CodingKeys) {
appendLiteral(LinkedDeviceReadReceiptRecord.columnName(column))
}
mutating func appendInterpolation(linkedDeviceReadReceiptColumnFullyQualified column: LinkedDeviceReadReceiptRecord.CodingKeys) {
appendLiteral(LinkedDeviceReadReceiptRecord.columnName(column, fullyQualified: true))
}
}
// MARK: - Deserialization
// TODO: Rework metadata to not include, for example, columns, column indices.
extension OWSLinkedDeviceReadReceipt {
// This method defines how to deserialize a model, given a
// database row. The recordType column is used to determine
// the corresponding model class.
class func fromRecord(_ record: LinkedDeviceReadReceiptRecord) throws -> OWSLinkedDeviceReadReceipt {
guard let recordId = record.id else {
throw SDSError.invalidValue
}
switch record.recordType {
case .linkedDeviceReadReceipt:
let uniqueId: String = record.uniqueId
let linkedDeviceReadReceiptSchemaVersion: UInt = record.linkedDeviceReadReceiptSchemaVersion
let messageIdTimestamp: UInt64 = record.messageIdTimestamp
let readTimestamp: UInt64 = record.readTimestamp
let senderPhoneNumber: String? = record.senderPhoneNumber
let senderUUID: String? = record.senderUUID
return OWSLinkedDeviceReadReceipt(uniqueId: uniqueId,
linkedDeviceReadReceiptSchemaVersion: linkedDeviceReadReceiptSchemaVersion,
messageIdTimestamp: messageIdTimestamp,
readTimestamp: readTimestamp,
senderPhoneNumber: senderPhoneNumber,
senderUUID: senderUUID)
default:
owsFailDebug("Unexpected record type: \(record.recordType)")
throw SDSError.invalidValue
}
}
}
// MARK: - SDSModel
extension OWSLinkedDeviceReadReceipt: SDSModel {
public var serializer: SDSSerializer {
// Any subclass can be cast to it's superclass,
// so the order of this switch statement matters.
// We need to do a "depth first" search by type.
switch self {
default:
return OWSLinkedDeviceReadReceiptSerializer(model: self)
}
}
public func asRecord() throws -> SDSRecord {
return try serializer.asRecord()
}
public var sdsTableName: String {
return LinkedDeviceReadReceiptRecord.databaseTableName
}
public static var table: SDSTableMetadata {
return OWSLinkedDeviceReadReceiptSerializer.table
}
}
// MARK: - Table Metadata
extension OWSLinkedDeviceReadReceiptSerializer {
// This defines all of the columns used in the table
// where this model (and any subclasses) are persisted.
static let idColumn = SDSColumnMetadata(columnName: "id", columnType: .primaryKey, columnIndex: 0)
static let recordTypeColumn = SDSColumnMetadata(columnName: "recordType", columnType: .int64, columnIndex: 1)
static let uniqueIdColumn = SDSColumnMetadata(columnName: "uniqueId", columnType: .unicodeString, isUnique: true, columnIndex: 2)
// Base class properties
static let linkedDeviceReadReceiptSchemaVersionColumn = SDSColumnMetadata(columnName: "linkedDeviceReadReceiptSchemaVersion", columnType: .int64, columnIndex: 3)
static let messageIdTimestampColumn = SDSColumnMetadata(columnName: "messageIdTimestamp", columnType: .int64, columnIndex: 4)
static let readTimestampColumn = SDSColumnMetadata(columnName: "readTimestamp", columnType: .int64, columnIndex: 5)
static let senderPhoneNumberColumn = SDSColumnMetadata(columnName: "senderPhoneNumber", columnType: .unicodeString, isOptional: true, columnIndex: 6)
static let senderUUIDColumn = SDSColumnMetadata(columnName: "senderUUID", columnType: .unicodeString, isOptional: true, columnIndex: 7)
// TODO: We should decide on a naming convention for
// tables that store models.
public static let table = SDSTableMetadata(collection: OWSLinkedDeviceReadReceipt.collection(),
tableName: "model_OWSLinkedDeviceReadReceipt",
columns: [
idColumn,
recordTypeColumn,
uniqueIdColumn,
linkedDeviceReadReceiptSchemaVersionColumn,
messageIdTimestampColumn,
readTimestampColumn,
senderPhoneNumberColumn,
senderUUIDColumn
])
}
// MARK: - Save/Remove/Update
@objc
public extension OWSLinkedDeviceReadReceipt {
func anyInsert(transaction: SDSAnyWriteTransaction) {
sdsSave(saveMode: .insert, transaction: transaction)
}
// This method is private; we should never use it directly.
// Instead, use anyUpdate(transaction:block:), so that we
// use the "update with" pattern.
private func anyUpdate(transaction: SDSAnyWriteTransaction) {
sdsSave(saveMode: .update, transaction: transaction)
}
@available(*, deprecated, message: "Use anyInsert() or anyUpdate() instead.")
func anyUpsert(transaction: SDSAnyWriteTransaction) {
let isInserting: Bool
if OWSLinkedDeviceReadReceipt.anyFetch(uniqueId: uniqueId, transaction: transaction) != nil {
isInserting = false
} else {
isInserting = true
}
sdsSave(saveMode: isInserting ? .insert : .update, transaction: transaction)
}
// This method is used by "updateWith..." methods.
//
// This model may be updated from many threads. We don't want to save
// our local copy (this instance) since it may be out of date. We also
// want to avoid re-saving a model that has been deleted. Therefore, we
// use "updateWith..." methods to:
//
// a) Update a property of this instance.
// b) If a copy of this model exists in the database, load an up-to-date copy,
// and update and save that copy.
// b) If a copy of this model _DOES NOT_ exist in the database, do _NOT_ save
// this local instance.
//
// After "updateWith...":
//
// a) Any copy of this model in the database will have been updated.
// b) The local property on this instance will always have been updated.
// c) Other properties on this instance may be out of date.
//
// All mutable properties of this class have been made read-only to
// prevent accidentally modifying them directly.
//
// This isn't a perfect arrangement, but in practice this will prevent
// data loss and will resolve all known issues.
func anyUpdate(transaction: SDSAnyWriteTransaction, block: (OWSLinkedDeviceReadReceipt) -> Void) {
block(self)
guard let dbCopy = type(of: self).anyFetch(uniqueId: uniqueId,
transaction: transaction) else {
return
}
// Don't apply the block twice to the same instance.
// It's at least unnecessary and actually wrong for some blocks.
// e.g. `block: { $0 in $0.someField++ }`
if dbCopy !== self {
block(dbCopy)
}
dbCopy.anyUpdate(transaction: transaction)
}
func anyRemove(transaction: SDSAnyWriteTransaction) {
sdsRemove(transaction: transaction)
}
func anyReload(transaction: SDSAnyReadTransaction) {
anyReload(transaction: transaction, ignoreMissing: false)
}
func anyReload(transaction: SDSAnyReadTransaction, ignoreMissing: Bool) {
guard let latestVersion = type(of: self).anyFetch(uniqueId: uniqueId, transaction: transaction) else {
if !ignoreMissing {
owsFailDebug("`latest` was unexpectedly nil")
}
return
}
setValuesForKeys(latestVersion.dictionaryValue)
}
}
// MARK: - OWSLinkedDeviceReadReceiptCursor
@objc
public class OWSLinkedDeviceReadReceiptCursor: NSObject {
private let cursor: RecordCursor<LinkedDeviceReadReceiptRecord>?
init(cursor: RecordCursor<LinkedDeviceReadReceiptRecord>?) {
self.cursor = cursor
}
public func next() throws -> OWSLinkedDeviceReadReceipt? {
guard let cursor = cursor else {
return nil
}
guard let record = try cursor.next() else {
return nil
}
return try OWSLinkedDeviceReadReceipt.fromRecord(record)
}
public func all() throws -> [OWSLinkedDeviceReadReceipt] {
var result = [OWSLinkedDeviceReadReceipt]()
while true {
guard let model = try next() else {
break
}
result.append(model)
}
return result
}
}
// MARK: - Obj-C Fetch
// TODO: We may eventually want to define some combination of:
//
// * fetchCursor, fetchOne, fetchAll, etc. (ala GRDB)
// * Optional "where clause" parameters for filtering.
// * Async flavors with completions.
//
// TODO: I've defined flavors that take a read transaction.
// Or we might take a "connection" if we end up having that class.
@objc
public extension OWSLinkedDeviceReadReceipt {
class func grdbFetchCursor(transaction: GRDBReadTransaction) -> OWSLinkedDeviceReadReceiptCursor {
let database = transaction.database
do {
let cursor = try LinkedDeviceReadReceiptRecord.fetchCursor(database)
return OWSLinkedDeviceReadReceiptCursor(cursor: cursor)
} catch {
owsFailDebug("Read failed: \(error)")
return OWSLinkedDeviceReadReceiptCursor(cursor: nil)
}
}
// Fetches a single model by "unique id".
class func anyFetch(uniqueId: String,
transaction: SDSAnyReadTransaction) -> OWSLinkedDeviceReadReceipt? {
assert(uniqueId.count > 0)
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return OWSLinkedDeviceReadReceipt.ydb_fetch(uniqueId: uniqueId, transaction: ydbTransaction)
case .grdbRead(let grdbTransaction):
let sql = "SELECT * FROM \(LinkedDeviceReadReceiptRecord.databaseTableName) WHERE \(linkedDeviceReadReceiptColumn: .uniqueId) = ?"
return grdbFetchOne(sql: sql, arguments: [uniqueId], transaction: grdbTransaction)
}
}
// Traverses all records.
// Records are not visited in any particular order.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
block: @escaping (OWSLinkedDeviceReadReceipt, UnsafeMutablePointer<ObjCBool>) -> Void) {
anyEnumerate(transaction: transaction, batched: false, block: block)
}
// Traverses all records.
// Records are not visited in any particular order.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
batched: Bool = false,
block: @escaping (OWSLinkedDeviceReadReceipt, UnsafeMutablePointer<ObjCBool>) -> Void) {
let batchSize = batched ? Batching.kDefaultBatchSize : 0
anyEnumerate(transaction: transaction, batchSize: batchSize, block: block)
}
// Traverses all records.
// Records are not visited in any particular order.
//
// If batchSize > 0, the enumeration is performed in autoreleased batches.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
batchSize: UInt,
block: @escaping (OWSLinkedDeviceReadReceipt, UnsafeMutablePointer<ObjCBool>) -> Void) {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
OWSLinkedDeviceReadReceipt.ydb_enumerateCollectionObjects(with: ydbTransaction) { (object, stop) in
guard let value = object as? OWSLinkedDeviceReadReceipt else {
owsFailDebug("unexpected object: \(type(of: object))")
return
}
block(value, stop)
}
case .grdbRead(let grdbTransaction):
do {
let cursor = OWSLinkedDeviceReadReceipt.grdbFetchCursor(transaction: grdbTransaction)
try Batching.loop(batchSize: batchSize,
loopBlock: { stop in
guard let value = try cursor.next() else {
stop.pointee = true
return
}
block(value, stop)
})
} catch let error {
owsFailDebug("Couldn't fetch models: \(error)")
}
}
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
anyEnumerateUniqueIds(transaction: transaction, batched: false, block: block)
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
batched: Bool = false,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
let batchSize = batched ? Batching.kDefaultBatchSize : 0
anyEnumerateUniqueIds(transaction: transaction, batchSize: batchSize, block: block)
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
//
// If batchSize > 0, the enumeration is performed in autoreleased batches.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
batchSize: UInt,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
ydbTransaction.enumerateKeys(inCollection: OWSLinkedDeviceReadReceipt.collection()) { (uniqueId, stop) in
block(uniqueId, stop)
}
case .grdbRead(let grdbTransaction):
grdbEnumerateUniqueIds(transaction: grdbTransaction,
sql: """
SELECT \(linkedDeviceReadReceiptColumn: .uniqueId)
FROM \(LinkedDeviceReadReceiptRecord.databaseTableName)
""",
batchSize: batchSize,
block: block)
}
}
// Does not order the results.
class func anyFetchAll(transaction: SDSAnyReadTransaction) -> [OWSLinkedDeviceReadReceipt] {
var result = [OWSLinkedDeviceReadReceipt]()
anyEnumerate(transaction: transaction) { (model, _) in
result.append(model)
}
return result
}
// Does not order the results.
class func anyAllUniqueIds(transaction: SDSAnyReadTransaction) -> [String] {
var result = [String]()
anyEnumerateUniqueIds(transaction: transaction) { (uniqueId, _) in
result.append(uniqueId)
}
return result
}
class func anyCount(transaction: SDSAnyReadTransaction) -> UInt {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return ydbTransaction.numberOfKeys(inCollection: OWSLinkedDeviceReadReceipt.collection())
case .grdbRead(let grdbTransaction):
return LinkedDeviceReadReceiptRecord.ows_fetchCount(grdbTransaction.database)
}
}
// WARNING: Do not use this method for any models which do cleanup
// in their anyWillRemove(), anyDidRemove() methods.
class func anyRemoveAllWithoutInstantation(transaction: SDSAnyWriteTransaction) {
switch transaction.writeTransaction {
case .yapWrite(let ydbTransaction):
ydbTransaction.removeAllObjects(inCollection: OWSLinkedDeviceReadReceipt.collection())
case .grdbWrite(let grdbTransaction):
do {
try LinkedDeviceReadReceiptRecord.deleteAll(grdbTransaction.database)
} catch {
owsFailDebug("deleteAll() failed: \(error)")
}
}
if shouldBeIndexedForFTS {
FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction)
}
}
class func anyRemoveAllWithInstantation(transaction: SDSAnyWriteTransaction) {
// To avoid mutationDuringEnumerationException, we need
// to remove the instances outside the enumeration.
let uniqueIds = anyAllUniqueIds(transaction: transaction)
var index: Int = 0
do {
try Batching.loop(batchSize: Batching.kDefaultBatchSize,
loopBlock: { stop in
guard index < uniqueIds.count else {
stop.pointee = true
return
}
let uniqueId = uniqueIds[index]
index = index + 1
guard let instance = anyFetch(uniqueId: uniqueId, transaction: transaction) else {
owsFailDebug("Missing instance.")
return
}
instance.anyRemove(transaction: transaction)
})
} catch {
owsFailDebug("Error: \(error)")
}
if shouldBeIndexedForFTS {
FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction)
}
}
class func anyExists(uniqueId: String,
transaction: SDSAnyReadTransaction) -> Bool {
assert(uniqueId.count > 0)
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return ydbTransaction.hasObject(forKey: uniqueId, inCollection: OWSLinkedDeviceReadReceipt.collection())
case .grdbRead(let grdbTransaction):
let sql = "SELECT EXISTS ( SELECT 1 FROM \(LinkedDeviceReadReceiptRecord.databaseTableName) WHERE \(linkedDeviceReadReceiptColumn: .uniqueId) = ? )"
let arguments: StatementArguments = [uniqueId]
return try! Bool.fetchOne(grdbTransaction.database, sql: sql, arguments: arguments) ?? false
}
}
}
// MARK: - Swift Fetch
public extension OWSLinkedDeviceReadReceipt {
class func grdbFetchCursor(sql: String,
arguments: StatementArguments = StatementArguments(),
transaction: GRDBReadTransaction) -> OWSLinkedDeviceReadReceiptCursor {
do {
let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true)
let cursor = try LinkedDeviceReadReceiptRecord.fetchCursor(transaction.database, sqlRequest)
return OWSLinkedDeviceReadReceiptCursor(cursor: cursor)
} catch {
Logger.error("sql: \(sql)")
owsFailDebug("Read failed: \(error)")
return OWSLinkedDeviceReadReceiptCursor(cursor: nil)
}
}
class func grdbFetchOne(sql: String,
arguments: StatementArguments = StatementArguments(),
transaction: GRDBReadTransaction) -> OWSLinkedDeviceReadReceipt? {
assert(sql.count > 0)
do {
let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true)
guard let record = try LinkedDeviceReadReceiptRecord.fetchOne(transaction.database, sqlRequest) else {
return nil
}
return try OWSLinkedDeviceReadReceipt.fromRecord(record)
} catch {
owsFailDebug("error: \(error)")
return nil
}
}
}
// MARK: - SDSSerializer
// The SDSSerializer protocol specifies how to insert and update the
// row that corresponds to this model.
class OWSLinkedDeviceReadReceiptSerializer: SDSSerializer {
private let model: OWSLinkedDeviceReadReceipt
public required init(model: OWSLinkedDeviceReadReceipt) {
self.model = model
}
// MARK: - Record
func asRecord() throws -> SDSRecord {
let id: Int64? = nil
let recordType: SDSRecordType = .linkedDeviceReadReceipt
let uniqueId: String = model.uniqueId
// Base class properties
let linkedDeviceReadReceiptSchemaVersion: UInt = model.linkedDeviceReadReceiptSchemaVersion
let messageIdTimestamp: UInt64 = model.messageIdTimestamp
let readTimestamp: UInt64 = model.readTimestamp
let senderPhoneNumber: String? = model.senderPhoneNumber
let senderUUID: String? = model.senderUUID
return LinkedDeviceReadReceiptRecord(id: id, recordType: recordType, uniqueId: uniqueId, linkedDeviceReadReceiptSchemaVersion: linkedDeviceReadReceiptSchemaVersion, messageIdTimestamp: messageIdTimestamp, readTimestamp: readTimestamp, senderPhoneNumber: senderPhoneNumber, senderUUID: senderUUID)
}
}
|
gpl-3.0
|
63cd467ff6c09cc3327581614b6becc2
| 39.875217 | 304 | 0.642612 | 5.34686 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.